我有一个函数可以将一个无值元素和一堆具有值的子元素添加到 xml 文件中,因此我将其编写为采用两个参数 $tag(String the Parent Node) 和 $hash(Array $elm=> $elm_value)
function addUser($tag, $hash)
{
$dom = new DOMDocuemnt();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->load('file');
$parent = $dom->createElement($tag);
foreach($hash as $elm => $value){
$n = $dom->createElement($elm, $value);
$parent->appendChild($n);
}
$dom->appendChild($parent);
$dom->save('file');
return $dom->saveXML();
}
唯一的问题是 $dom->appendChild($parent)
在根元素的结束标记之后附加所有内容,弄乱了我的 xml 文件。所以我尝试了 $dom->insertBefore($parent)
得到了相同的结果。所以我尝试了 $xpath = new DOMXPath($dom); $root = $xpath->query('/')->item(0); $root->appendChild($parent);
。相同的结果。然后我尝试使用 $dom->getElementsByTagName(name of root)->item(0);
选择根元素,当它真正起作用时我感到很惊讶!但是如果我不知道标签名称怎么办?是否有另一种方法来选择根元素,以便调用appendChild或inserBefore将在根结束标记之前而不是之后添加元素?
最佳答案
这似乎有效:
初始 XML 文件 -
<!-- test.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node Id="1">
<Clicks>click1</Clicks>
</node>
</root>
PHP-
<?php
function addUser($tag, $hash) {
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->load('test.xml');
$parent = $dom->createElement($tag);
$dom->documentElement->appendChild($parent);
foreach($hash as $elm => $value){
$n = $dom->createElement($elm);
$n->appendChild( $dom->createTextNode( $value ) );
$parent->appendChild($n);
}
$dom->save('test.xml');
}
$arr = array( 'name' => 'pushpesh', 'age' => 30, 'profession' => 'SO bugger' );
addUser('user', $arr);
XML 文件现在是 -
<!-- test.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node Id="1">
<Clicks>click1</Clicks>
</node>
<user>
<name>pushpesh</name>
<age>30</age>
<profession>SO bugger</profession>
</user>
</root>
希望这有帮助。
关于php - 当在根之后的 DOMDocument 附加节点上调用时,appendChild 和 insertBefore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10975625/