user3614185
user3614185

Reputation: 17

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

Upvotes: 0

Views: 907

Answers (2)

Jan
Jan

Reputation: 46

This way you run through all sighting elements and within those elements you get all child elements. Now you can store all your data in an array and display it later.

$data = array();
$xml = new DOMDocument();
$xml->load($otherdata);

$nodes = $xml->getElementsByTagName('sighting');
foreach ($nodes as $node) {
    $children = $node->childNodes; 
    $i=0;
    foreach ($children as $child) { 
        $data[$i][] = $child->nodeValue;
    }
}

This way you can update the name element and save the xml doc.

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

$nodes = $xml->getElementsByTagName('sighting');
foreach ($nodes->item as $node) {
    $children = $node->childNodes; 
    foreach ($children as $child) { 
        if ($child->nodeName == 'name')
            $child->nodeValue = 'Not Johnny';
    } 
}

$xml->save($file);

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167516

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;
 }

Upvotes: 1

Related Questions