Read XML Child Node (Xpath)Values of Specific Parent Tag
I need the Node values of child tag(person name) from specific parent tag (Person) only not any of other other child Node value.
for Ex:
I need the Node values of all Person Name only,
since name tag is same for both person name and its sub child name (company name) also, i am getting both person name & company name.
I am using Dom getElementsByTagName function.Please any of one help me how to grab the values of specific Tag level only. The code as follows.
<?php
$vXML="
<info>
<person>
<name>person 1 </name>
<email>email1@yahoo.com</email>
<company>
<name>company 1 </name>
</company>
</person>
<person>
<name> person2 </name>
<email>email2@yahoo.com</email>
<company>
<name>company 1 </name>
</company>
</person>
</info>";
$doc = DOMDocument::loadXML($vXML);
$vObjList = $doc->getElementsByTagName('name');
foreach( $vObjList as $oNode )
{
var_dump($oNode->nodeValue);
}
?>
The Simplest and Durable solution using Xpath as folows
The Simple way for reading XML for the given parent node is by using XPath function.Just give the Path of the node in the Xpath function.
which is fast and array of node values as follows.
$objSimpleXML = new SimpleXMLElement($vXML);
$objXMLResp = $objSimpleXML->xpath('/info/person/name');
var_dump($objXMLResp);