tags:

views:

101

answers:

2

How can I parse an XML document like this:

<feed>
  <item>
    <element-name>Element value</element-name>
  </item>
</feed>

If I try the following, it doesn't work:

$xmlObject = simplexml_load_string($xmlString);

foreach($xmlObject->item as $item) {
    $elementName= $item->element-name; // Obviously doesn't work.
}

I've tried:

$item->element_name;
$item->elementname;
$item->elementName;

None work. How do I access this element's value?

+1  A: 

You could use something like this:

$name = "element-name";
$item->{$name};
nickf
That did the trick. Thanks for the help!
Geoff
A: 

simplexml_load_string does not like it when you try and pass it element nodes with dashes/hyphens (-).

You have two options here.

Encapsulate the element name with curly braces ({}):

$elementName = $item->{'element-name'};

Or turn it into a variable you can replace out:

$elementNameNode = 'element-name';
$elementName = $item->$elementNameNode;
random