Search code examples
phpxmlxpathsimplexml

how to select nodevalue based on another nodevalue via php ?


I have a xml file which contains this :

<ns1:Response xmlns:ns1="http://example.com/">
- <ns1:return>
   <ns1:mid>39824</ns1:mid> 
   <ns1:serverType>4</ns1:serverType> 
   <ns1:size>5</ns1:size> 
 </ns1:return>
- <ns1:return>....
</ns1:return>

Now I want to get nodevalue of mid where nodevalue size has 5, I tried following code but no results:

$doc = new DOMDocument();
$doc->load($file);

$xpath = new DOMXPath($doc);

$query = '//Response/return/size[.="5"]/mid';

$entries = $xpath->evaluate($query);

So how can I do that ?

thanks in advance


Solution

  • You can also use following::sibling in this case. Get mid value where its following sibling is size with text equal to 5. Rough example:

    $query = 'string(//ns1:Response/ns1:return/ns1:mid[following-sibling::ns1:size[text()="5"]])';
    

    Sample Output