根据php中父节点的属性将子句附加到xml
I would like to ask, how to easily append new node to the end of found node in php. Lets say I have xml like this:
<Root>
<child id=1>
<text>smth</text>
</child>
</Root>
I want to find the child element with id 1 and then append another node as last. I was trying to find an answer, but it either answer how to find it, or how to write into it, unfortunately I was not able to put it together.
I would be really happy if someone can help me with this.
我想问一下,如何轻松地将新节点附加到php中找到的节点的末尾。 让我们说 我有这样的xml: p>
&lt; Root&gt;
&lt; child id = 1&gt;
&lt; text&gt; smth&lt; / text&gt;
&lt; / child&gt ;
&lt; / root&gt;
code> pre>
我想找到id为1的子元素,然后追加另一个节点作为最后一个。
我试图找到答案 ,但它要么回答如何找到它,要么如何写入它,不幸的是我无法把它放在一起。 p>
如果有人可以帮助我,我会很高兴的 。 p>
div>
You can use the xpath
to find the relevant node (based on the id
) and then use the addChild
to add new child-node to the node you just found:
$str =<<< END
<Root>
<child id="1">
<text>smth</text>
</child>
</Root>
END;
$result = simplexml_load_string($str);
$child = $result->xpath("*[@id='1']")[0];
$child->addChild('text', 'node value');
// The part from here is only to make the output pretty-xml
// instead you can just use $result->saveXML()
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($result->saveXML());
var_dump($dom->saveXML());
The output will be:
string(115) "<?xml version="1.0"?>
<Root>
<child id="1">
<text>smth</text>
<text>node value</text>
</child>
</Root>
"
In DOM, you use Xpath to find nodes, DOMDocument::create*()
to create the nodes and methods like DOMNode::appendChild()
to put them into the document.
$xml =<<< END
<Root>
<child id="1">
<text>smth</text>
</child>
</Root>
END;
$document = new DOMDocument("1.0");
$document->preserveWhiteSpace = false;
$document->formatOutput = true;
$document->loadXml($xml);
$xpath = new DOMXpath($document);
foreach ($xpath->evaluate('//*[@id="1"][1]') as $parentNode) {
$parentNode
->appendChild($document->createElement('text'))
->appendChild($document->createTextNode('node value'));
}
echo $document->saveXML();
Output:
<?xml version="1.0"?>
<Root>
<child id="1">
<text>smth</text>
<text>node value</text>
</child>
</Root>
For huge XML files you can use XMLReader/XMLWriter, but you can not modify the document. You will have to read the original step by step and write a modified copy.