php xmlreader get child details from complex node

335 Views Asked by At

OK so I am not sure what the correct term for this part of the node is but I am trying to get the data from the Location1 node.

Here is the XML

<ID>123344</ID>
<Name><![CDATA[The Pavillion]]></Name>
<Date>2014-07-07</Date>
<Country>United Kingdom</Country>
<Location1 GeonameID="8000001"><en><![CDATA[England]]></en></Location1>
<Location2 GeonameID="8000911"><en><![CDATA[West Yorkshire]]></en></Location2>

Here is how I am getting the correct values for ID and Name

 if ($xml->name == 'ID') {   $xml->read();   $ref = $xml->value;    }
 if ($xml->name == 'Name') {   $xml->read();   $name = $xml->value;    }

But how do I get the value of the Location1 node which would be England. I have tried this but it does not work.

if ($xml->name == 'Location1') {   $xml->read();   $name = $xml->value->en;    }

I am used to using simplexml rather than xmlreader, but I am lost on how to get a value from anything other than a simple node.

Much appreciated

1

There are 1 best solutions below

0
On

XMLReader has no automatic mapping. Stuff like $xml->value->en; will not work.

XMLReader pulls a node from the XML with $xml->read();. You have to possibilities. Put some logic inside the condition that validates Location* tagname. It needs to read the child nodes to get the en element node.

Or let XMLReader expand the outer node (the parent node of the XML fragment you posted) into DOM. You can then use Xpath on it or convert it to SimpleXMLElement.