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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程