Using XML node names with hyphens in PHP

williamsdb picture williamsdb · Sep 3, 2010 · Viewed 15.4k times · Source

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?

Answer

codaddict picture codaddict · Sep 3, 2010

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'}