我正在使用PHP的DOMDocument来构建一个新的xml文件。
我需要遍历一个父/子数组并将它们添加到我的xml中。如果父项不存在,我想创建它然后添加一个子项。如果确实存在,我想将子元素添加到该元素。
基本上,这个:
$arr = array(
'fruit' => 'apple',
'car' => 'toyota',
'fruit' => 'kiwi',
'car' => 'ford'
)
需要成为这个:
<categories>
<fruit>
<apple/>
<kiwi/>
</fruit>
<car>
<toyota/>
<ford/>
</car>
</categories>
我正在寻找类似的东西:
// create category element
$categories = $dom->createElement('categories');
// add each element to $categories
foreach($arr as $parent => $child){
// try to find pre-existing parent
$tmp_parent = $categories->some_function_to_find_child( $parent );
// ..or create new parent
if( $tmp_parent == null ) {
$tmp_parent = $categories->appendElement( $parent );
}
// add child
$tmp_parent->appendElement( $child );
}
// add $categories to $dom
$dom->appendChild( $categories );
答案 0 :(得分:2)
使用DOMXPath搜索现有元素:
$dom = new DOMDocument();
$xpath = new DOMXPath($dom);
// create category element
$categories = $dom->createElement('categories');
// add each element to $categories
foreach ($arr as $parent => $child) {
// try to find pre-existing parent
$tmp_parent = $xpath->query($parent, $categories);
// ..or create new parent
if ($tmp_parent->length == 0) {
$categories->appendChild($dom->createElement($parent));
} else {
// add child
$tmp_parent->item(0)->appendChild($dom->createElement($child));
}
}
// add $categories to $dom
$dom->appendChild($categories);
print_r($dom->saveXML());