如果 PHP DOMDocument 中不存在则创建元素
Create element if it does not exist in a PHP DOMDocument
我正在使用 PHP 的 DOMDocument 构建一个新的 xml 文件。
我需要遍历 parent/children 数组并将它们添加到我的 xml 中。如果parent不存在,我想创建它,然后添加一个child。如果确实存在,我想将 child 添加到该元素。
本质上,这个:
$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 );
使用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());
我正在使用 PHP 的 DOMDocument 构建一个新的 xml 文件。
我需要遍历 parent/children 数组并将它们添加到我的 xml 中。如果parent不存在,我想创建它,然后添加一个child。如果确实存在,我想将 child 添加到该元素。
本质上,这个:
$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 );
使用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());