drzbc6003 2015-10-20 11:00
浏览 55
已采纳

PHP:从PHP更新XML并保存

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++;
  • 写回答

3条回答 默认 最新

  • duanjiaolia97750 2015-10-20 13:39
    关注

    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;                  
        } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?