42

I am trying to extract some data from XML but when I execute the following I get a

Warning: Invalid argument supplied for foreach() in ...

Code Example:

foreach ($xml->custom-field-value as $milestone)
{
    ...     
}

It works fine for node names that are single words so I am guessing that it doesn't like the hyphens. Do I need to escape them and if so how?

hakre
  • 193,403
  • 52
  • 435
  • 836
williamsdb
  • 1,054
  • 2
  • 17
  • 29

1 Answers1

80

From PHP manual:

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

In your case you do:

$xml->{'custom-field-value'}
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 2
    This may be marked a duplicate question, but I found this Q/A combo much more useful then the 'original' as it was right to the point concerning my issue. – Melikoth Apr 11 '15 at 22:14
  • 1
    Coming here in 2020 to say the same thing. This post showed as first result in my search. – a coder Sep 01 '20 at 18:23