dongshan7060 2014-05-19 10:35
浏览 51

在读取节点值并在PHP中将其递增1之后,将节点值写回xml文件

Thanks for devoting time. I am very new in php like an Infant.

I have a Xml file counter.xml like.

<?xml version="1.0"?>
<countIt>
<number>50</number></countIt>

I can read this file By SimpleXML as follows:

$content=simplexml_load_file("counter.xml");
$addid=$content->countIt->number;

Now I want to read this value (number---> id i.e. 55) after some operations like increment by 1, I want to save this new value of the node in file too. that means the new value must reflect into xml file.

I am stuck with this problem. I tried DOM but I got only help to create a new Xml File.

Please Help

SOLUTION:

<?php
$domObj= new DOMDocument(); 
$domObj->load("counter.xml");
$value= $domObj->getElementsByTagName("countIt");
$newVal = 0 ;
foreach( $value as $val) 
{ 
 $ints = $val->getElementsByTagName("number"); 
 $intVal  = $ints->item(0)->nodeValue; 
 $newVal = $intVal+1;
 $domObj->getElementsByTagName("number")->item(0)->nodeValue = $newVal; 
 $domObj->save('counter.xml');
}  
?>
  • 写回答

1条回答 默认 最新

  • dongraa1986 2014-05-19 20:28
    关注

    This example makes use of the xpath() function to select the node to be changed:

    $xml = simplexml_load_string($x); // assume XML in $x
    
    // get the node
    $target = $xml->xpath("/countIt/number");
    
    // change it
    $target[0][0] = (int)$target[0] + 1;
    

    see it working: https://eval.in/153679

    Comments:

    • xpath will return an array to $target, in this example it has 1 element.
    • $target[0] = 50, for safety, I cast it to integer with (int) before adding
    • for saving the new XML, look into simplexml on PHP.net for asXML().
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)