0

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

2 Answers2

1

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;
 }
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • thank for the fast reply, unfortunately there are multiple elements I need to get...i didn't list them all in the same code.. – user3614185 Jun 15 '14 at 08:49
1

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);
Jan
  • 46
  • 3