SimpleXML PHP - 从任何节点更改值 [英] SimpleXML PHP - Change Value from any Node

查看:32
本文介绍了SimpleXML PHP - 从任何节点更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会在 stackoverflow 上找到我正在锁定的所有内容.但现在我需要你的帮助.

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

我的示例 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>

现在我需要从更改节点更改文本.但这是一个示例 xml.我不知道 xml 的结构.我只有更改名称.有没有像 js getElementsByTagName("change")当我想从更改节点更改文本时要做什么

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

推荐答案

使用 xpath():

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

这将选择所有以 change 开头的节点.// 将从树中的任何位置选择它们.结果以 SimpleXML 元素的形式存储在 $changes 中的数组中.

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.

现在更改选定的节点:

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

看看更改后的 XML:

Take a look at the changed XML:

echo $xml->asXML();

看看它是否有效:https://eval.in/231427

这篇关于SimpleXML PHP - 从任何节点更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆