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;
$i开发者_开发问答tem->elementname;
$item->elementName;
None work. How do I access this element's value?
You could use something like this:
$name = "element-name";
$item->{$name};
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;
精彩评论