使用 simpleXML 重命名多个属性
<root>
<gallery name="First"/>
<gallery name="Second"/>
<gallery name="Third"/>
</root>
我试图一次重命名多个“name”属性:
$rename = array();
foreach($_POST['name'] as $value) {
$rename[] = $value;
}
$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$gallery = $objXML->xpath('/root/gallery/@name');
print_r($gallery);
print_r($rename);
$objXML->asXML(XML_FILE_NAME);
返回:
Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => First ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Second ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Third ) ) )
Array ( [0] => First New [1] => Second New [2] => Third New )
如何让 php 将新值保存回 XML?是否需要另一个 foreach 循环?代码似乎已经变得太复杂了。
我正在尝试这个,但没有骰子:
foreach( $objXML->xpath('/root/gallery/@name') as $gallery ) {
$gallery = $_POST['name'];
}
<root>
<gallery name="First"/>
<gallery name="Second"/>
<gallery name="Third"/>
</root>
I'm trying to rename multiple "name" attributes at once:
$rename = array();
foreach($_POST['name'] as $value) {
$rename[] = $value;
}
$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$gallery = $objXML->xpath('/root/gallery/@name');
print_r($gallery);
print_r($rename);
$objXML->asXML(XML_FILE_NAME);
Returns:
Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => First ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Second ) ) [2] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => Third ) ) )
Array ( [0] => First New [1] => Second New [2] => Third New )
How can I get php to save the New values back to the XML? Does it need another foreach loop? The code seems to be getting too complex already.
I'm trying this, but no dice:
foreach( $objXML->xpath('/root/gallery/@name') as $gallery ) {
$gallery = $_POST['name'];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Simplexml 构建为仅返回节点。这很奇怪,但是
'/root/gallery/@name'
和'/root/gallery'
。这两个查询
将返回相同的实例
因此更改节点属性的唯一方法是使用数组语法
Simplexml is buid to returns node only. That's weird, but
'/root/gallery/@name'
and'/root/gallery'
.These two queries
will return the same instances
So the only way for changing the attribute of a node is with the array syntaxe