dsjswclzh40259075 2017-01-05 15:46
浏览 43
已采纳

根据php中的特定属性更新xml文件中的单个节点

I have a xml file named test.xml with the following structure.

<?xml version="1.0"?>
    <markers>
       <marker id="1" name="12" signal="23"/>
       <marker id="2" name="12" signal="5"/>
       <marker id="3" name="12" signal="6"/>
       <marker id="4" name="12" signal="0"/>
</markers>

I make an ajax request to my server code where I sent an ID and want to increase the signal attribute in test.xml by 1.

For example if I send id=3 then the signal attribute of the marker node with id of 3 should get 7 and the file should be saved. I don't want to rewrite the whole file due to some issues but only update an attribute.

I tried this but I think it's far away from the right answer. Can anyone help?

$id=$_POST['id'];

$xml = new SimpleXMLElement('test.xml');

foreach( $xml->xpath( 'marker' ) as $xml_row ){
    if( $xml_row->attributes( 'id' ) == $id ){
        $xml_row->attr( 'signals ') = $xml_row->attributes( 'signals' ) + 1;

    }
}
$xml->saveXML( 'test.xml' );
  • 写回答

1条回答 默认 最新

  • dongzi1959 2017-01-05 16:55
    关注

    I figured out the answer myself:

    $xmldoc = new DOMDocument();
    $xmldoc->load('test.xml');
    foreach ($xmldoc->getElementsByTagName('marker') as $feeditem) {
        if($feeditem->getAttribute('id')==$id){
            $sig=$feeditem->getAttribute('signal');
            $sig++;
            $feeditem->setAttribute('signal',$sig);
        }
    
    
    }
    $xmldoc->save('test.xml');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器