Update only Xml node (PHP5)


Since this is XML you may want to consider using PHP’s Dom class (not
Dom XML) to do the updating.

Assuming you have this file: book.xml

<sample>
<exo id=”1″ value=”Test” />
<exo id=”2″ value=”Test2″ />
</sample>

This example code will search for all the tags with ‘exo’ and change
the one whose id==’1′. It will then write back the file.

<?php
$dom=new DOMDocument();
$dom->load(‘book.xml’);
$dom->formatOutput = true;
echo $dom->saveXML(); // show before file
$allnodes = $dom->getElementsByTagName(‘exo’);
foreach ($allnodes as $node) {
if ($node->nodeName==’exo’ and $node->getAttribute(‘id’)==’1′) {
$val=$node->getAttribute(‘value’) . ‘ updated’;
$node->setAttribute ( ‘value’, $val );
}
}
echo $dom->saveXML(); //show after file
$dom->save(‘book.xml’);
exit;
?>

Advertisements
%d bloggers like this: