doufuxi7093 2014-12-05 23:00
浏览 72
已采纳

SimpleXML PHP - 从任何节点更改值[重复]

This question already has an answer here:

Normaly i find everything at stackoverflow what iam locking for. but now i need ur help.

my example xml:

<xml>
  <first>
    <change>Text to change</change>
  </first>
  <second>
    <change1>Text to change</change1>
    <change2>Text to change</change2>
    <change3>Text to change</change3>
  </second>
</xml>

Now i need to change the text from the change nodes. But this is a example xml. i dont know the structure from the xml. i only have the change names. is there sth like in js getElementsByTagName("change") what is to when i want to change the text from the change nodes

thanks guys... and sry for my english ;)

</div>
  • 写回答

1条回答 默认 最新

  • dongxu1668 2014-12-05 23:44
    关注

    Use xpath():

    $xml = simplexml_load_string($x); // assume XML in $x
    $changes = $xml->xpath("//*[starts-with(local-name(), 'change')]");
    

    This will select all nodes starting with change. The // will select them from whatever position in the tree. The results are stored as SimpleXML elements in an array in $changes.

    Now change the selected nodes:

    foreach ($changes as $change) 
        $change[0] = "New Text";
    

    Take a look at the changed XML:

    echo $xml->asXML();
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?