I’m stuck with this and can’t find the answer on the net. I want to use DOM to load XML.
I have an XML with the following scheme:
<type1>
<other>...</other>
<number>bla</number>
<other>...</other>
</type1>
<type1>
<other>...</other>
<number>bla</number>
<other>...</other>
</type1>
...
<type2>
<other>...</other>
<number>bla</number>
<other>...</other>
</type2>
<type2>
<other>...</other>
<number>bla</number>
<other>...</other>
</type2>
Both data of type1 and type2 occur multiple times. The tag number occurs in both types.
When I use
$searchNode = $xmlHandler->getElementsByTagName("number");
I get numbers of both types. How can I get only the numbers of type1 or type2?
UPDATE:
Based on the suggestions of Kami and Ikku I have solved it for DOM. Below the working code:
<?php
$xmlHandler = new DOMDocument();
$xmlHandler->load("xmldocumentname.xml");
$xpath = new DOMXPath($xmlHandler);
$searchNodes = $xpath->query("/type1");
foreach( $searchNodes as $searchNode ) {
$xmlItem = $searchNode->getElementsByTagName("number");
$number = $xmlItem->item(0)->nodeValue;
$xmlItem = $searchNode->getElementsByTagName("other");
$other = $xmlItem->item(0)->nodeValue;
echo "NUMBER=" . $number . "<br>";
echo "OTHER=" . $other . "<br>";
}
?>
You need to expand your search to allow for the specific value for a parent. The
getElementsByTagNamelimits you to the name of the tag you are looking for so it cannot do a general search. Use a more generalised search. I am usingxpathfrom thesimplexmllibrary in the example below.To do the same with DOM – There is an extra step of creating an xpath object but this is required to make the searching easier.
The above is untested; so modify as required.