dongyuqi3808 2015-06-28 14:51
浏览 101
已采纳

属性为的XML更改值

With PHP I want to change the value in the node where attribute is something I specify. The XML file:

<?xml version='1.0' standalone='yes'?>
<days>
<Maandag id="1">0</Maandag>
<Dinsdag     id="2">0</Dinsdag>
<Woensdag    id="3">0</Woensdag>
<Donderdag   id="4">0</Donderdag>
<Vrijdag     id="5">0</Vrijdag>
<Zaterdag    id="6">0</Zaterdag>
<Zonday  id="0">0</Zonday>  
</days>

For example: Today is Monday so jddayofweek(0) = 1 Then the value of the node with id=1 needs to change, so in the end we get:

<?xml version='1.0' standalone='yes'?>
<days>
<Maandag id="1">3</Maandag>
<Dinsdag     id="2">0</Dinsdag>
<Woensdag    id="3">0</Woensdag>
<Donderdag   id="4">0</Donderdag>
<Vrijdag     id="5">0</Vrijdag>
<Zaterdag    id="6">0</Zaterdag>
<Zonday  id="0">0</Zonday>  
</days>

How do I do this in PHP?

</div>
  • 写回答

3条回答 默认 最新

  • douyong5825 2015-06-28 18:39
    关注

    I'd recommend simpleXML, because it is - well - simple:

    $xml = simplexml_load_string($x); // assume XML in $x
    $id = 1; 
    
    $day = $xml->xpath("*[@id=`$id`]")[0];
    $day[0] = 5;
    

    see the result:

    echo $xml->asXML();
    

    Comments:

    • the xpath-expression will select the day by $id and give back an array of SimpleXML-elements.
    • select the 1st element (index [0]) and store it in $day (requires PHP >= 5.4)

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

    Thinking further

    If you make that XML, add clarity and flexibility by making it like this:

    <days>
        <day name="Maandag" id="1">0</day>
        <day name="Dinsdag" id="2">0</day>
        <etc />
    </days>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序