1

I'm trying to update 1 particular node in an pre-existing xml file from php. The problem i'm having is that it doesn't seem to be saving to the xml file. Not sure why and any help here will be appreciated!

<?php       
$itemNumber = $_GET["itemNumberField"];

$xmlFile = "items.xml";

if(file_exists($xmlFile))
{           

    // $doc = new DOMDocument('1.0');
    // $doc->load($xmlFile);

    $doc = DOMDocument::load($xmlFile); 

    $item = $doc->getElementsByTagName("item");

    foreach($item as $node) 
    {   
        $itemNumberNode = $node->getElementsByTagName("itemNumber");
        $itemNumberNode = $itemNumberNode->item(0)->nodeValue;

        $qtyNode = $node->getElementsByTagName("quantity");
        $qtyNode = $qtyNode->item(0)->nodeValue;                

        if ($itemNumberNode == $itemNumber)
        {
            $qtyNode++;

            echo $qtyNode;                  
        }
    }        
} 

else 
{       
    echo "file doesn't exist! <br/>";       
}

$doc->save($xmlFile);

?>

Edit: Just to clarify, the adding to the node seems to be fine.

Solution: Turns out the reason it didn't save was because node of the adding. i had to either directly update it or assign an updated value to it.

$qtyNode = $node->getElementsByTagName("quantity");
$qtyNode = $qtyNode->item(0);
...
$qtyNode->nodeValue++;
2
  • 1
    where are you trying to save the file? Local or remote? Commented Oct 20, 2015 at 11:45
  • @bboni it's on a remote server. Commented Oct 20, 2015 at 11:51

3 Answers 3

2

I've just coded something similar, and found out that $doc->saveXML() just builds up the outgoing xml string. I added a file_put_contents for writing to the xml file and worked fine.

file_put_contents($xmlFile, $doc->saveXML());
Sign up to request clarification or add additional context in comments.

Comments

1

You COPY the scalar value (string) into a variable. Then you change the variable.

    $qtyNode = $qtyNode->item(0)->nodeValue;                

    if ($itemNumberNode == $itemNumber)
    {
        $qtyNode++;

        echo $qtyNode;                  
    } 

$qtyNode is not a DOMNode object, but a string variable.

You will have to change the DOMNode::$nodeValue property directly or assign the variable to it.

    $qtyNode = $qtyNode->item(0);                

    if ($itemNumberNode == $itemNumber)
    {
        $qtyNode->nodeValue++;

        echo $qtyNode->nodeValue;                  
    } 

Comments

1

Chmod the folder in which you want to save xml file: set permissions to maxiamally 775.

If this not works try using Curl

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.