I’m trying to add +1 to a number in my XML document, and if its just one no problemo, but… If I want to update 2 nodes it goes wrong?
Here is what I have tried:
$xml = new DOMDocument("1.0", "ISO-8859-1");
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML('<?xml version="1.0"?>
<friends>
<friend id="1">
<name>MyTest</name>
<games>5</games>
<wins>3</wins>
</friend>
</friends>');
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
$library = $xml->documentElement;
$xpath = new DOMXPath($xml);
$xpath2 = new DOMXPath($xml);
$result = $xpath->query('//friend[@id="1"]/games');
if($result){
$cgames = $xpath->query('//friend[@id="1"]/games')->item(0);
$cgames = $cgames->nodeValue;
$result->item(0)->nodeValue = $cgames+1;
$cwins = $xpath->query('//friend[@id="1"]/wins')->item(0);
$cwins = $cwins->nodeValue;
$result->item(0)->nodeValue = $cwins+1;
echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
}
When doing this I only update and its new value would be 4? It should be 6 and should be 4… What am I doing wrong?
Please help and thanks in advance 🙂
Add
$result2since you are trying to update/winson/gamessearchand remove
$xpath2 = new DOMXPath($xml);, you don’t need 2XPathsCodepad Example