php - 如果 PHP DOMDocument 中不存在则创建元素

标签 php xml domdocument

我正在使用 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 );

最佳答案

使用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 - 如果 PHP DOMDocument 中不存在则创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28329595/

相关文章:

PHP DOMDocument - 如何添加命名空间声明?

php - 使用 PHPUnit 模拟类时如何防止调用原始方法?

PHP:电子邮件验证并接受来自特定域的电子邮件地址

xml - 忽略流式 xml 管道中的子树

xml - 使用Powershell操纵xml文件dom并创建另一个xml文件

php - 在 PHP 中,如何使用 DOMDocument 类替换 IMG 标签的 src= 属性?

php - 如何卸载 Phabricator

php - Bootstrap 4 明信片在我的网站上似乎有所不同

苹果手机 : NSXMLParser fails to identify HTML special entity &amp;

php - 在 PHP 中添加到非标记 HTML 文本