Search code examples
phpxpathxpathquery

Get xml results where element node is equal to string


ok, xml file looks like this, it is set to a variable $otherdata

<result>
 <sighting>
  <name>Johhny</name>
  <last>smith</last>
  <phone>5551234</phone>
 </sighting>
 </result>

and php code looks like this

$dom = new DOMDocument;
$dom ->load($otherdata);
$xpath = new DomXpath($dom);

$query = '//result/sighting[name = "Johhny"]/.';
$entries = $xpath->query($query);

foreach ($entries as $entry) {
 $newlat = $entry->textContent;

 echo $newlat
 }

where I am running into trouble is trying to get the value in the 'last' and 'phone' attribute and set it equal to variable to store and echo later...thanks


Solution

  • You could use

    $query = '//result/sighting[name = "Johhny"]';
    

    as the path as that way you directly select the sighting element(s). Then you can read out the contents and change it with

    foreach ($entries as $entry) {
     $last = $entry->getElementsByTagName('last')->item(0)->textContent;
     $entry->getElementsByTagName('name')->textContent = $newName;
     }