[英]Add child to xml with PHP simpleXml
我在simpleXml和添加新项目方面遇到问题。 这是我的xml:
<?xml version="1.0" encoding="utf-8"?>
<root>
<items>
<item>abc</item>
<item>def</item>
<item>ghi</item>
</items>
</root>
我正在使用以下php代码:
$xml = simplexml_load_file("myxml.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$newItem = $sxe->addChild("items");
$newItem->addChild("item", $newValue);
$sxe->asXML("myxml.xml");
结果如下:
<?xml version="1.0" encoding="utf-8"?>
<root>
<items>
<item>abc</item>
<item>def</item>
<item>ghi</item>
</items>
<items>
<item>jkl</item>
</items>
</root>
这为我创建了新项目节点,但我想将项目添加到相同的现有项目节点。
那么,您不应该创建新项目节点:
$xml = simplexml_load_file("myxml.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$itemsNode = $sxe->items[0];
$itemsNode->addChild("item", $newValue);
$sxe->asXML("myxml.xml");
您可以对接受子项附加的SimpleXML对象使用此类。
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
/**
* Add SimpleXMLElement code into a SimpleXMLElement
*
* @param MySimpleXMLElement $append
*/
public function appendXML($append)
{
if ($append) {
if (strlen(trim((string)$append)) == 0) {
$xml = $this->addChild($append->getName());
} else {
$xml = $this->addChild($append->getName(), (string)$append);
}
foreach ($append->children() as $child) {
$xml->appendXML($child);
}
foreach ($append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
}
您是否尝试过以下方式
$newItem->root->items[0]->addChild("item","Test");
要么
$newItem->root->items->addChild("item","Test");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.