Search code examples
phpxmlsimplexml

Trouble adding up value xml


I'm looking to increment an XML node by 1 each time a visitor visits the page.

Here is what I currently have, but it keeps returning a value of 1...

<?php

$xPostName =   $xml->up;

//load xml file to edit

$xml = simplexml_load_file($_GET['id'].'/info.xml');

$xml->up = $xPostName +1;

// save the updated document

$xml->asXML($_GET['id'].'/info.xml');

echo "done";

?>

Solution

  • The problem is that you set $xPostName before you load the file, so there is no value at this point, and then add 1 to this to update the value...

    $xPostName =   $xml->up;
    //load xml file to edit
    $xml = simplexml_load_file($_GET['id'].'/info.xml');
    $xml->up = $xPostName +1;
    

    So move this to after loading the file...

    //load xml file to edit
    $xml = simplexml_load_file($_GET['id'].'/info.xml');
    $xPostName =   $xml->up;
    $xml->up = $xPostName +1;
    

    Or just increment the value directly...

    $xml = simplexml_load_file('out.xml');
    
    $xml->up +=1;