SimpleXML PHP - Change Value from any Node [duplicate]

佐手、 提交于 2019-12-24 12:08:19

问题


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 ;)


回答1:


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



来源:https://stackoverflow.com/questions/27326066/simplexml-php-change-value-from-any-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!