当子 PHP 中不存在时,将元素添加到 XML


Add element to XML when not existing in child PHP

<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<a>product a</a>
<b>data</b>
<c>data</c>
</product>
<product>
<a>product b</a>
<c>data</c>
</product>
</products>

当缺少子元素时,我想将其添加到 XML 文件中。 所以<产品>这样结束。无需添加任何数据,只需添加元素即可。

<product>
<a>data</a>
<c>data</c>
<b></b>
</product>

这可以用 simplexml 完成吗?

<?php
$xml = simplexml_load_file("xml.xml", NULL, TRUE);
foreach ($xml->children() as $child) {}

绝对是可能的。下面是如何执行此操作的示例(假设您不担心子元素出现的顺序):

$xml = new SimpleXMLElement('xml.xml', NULL, TRUE);
foreach ($xml->children() as $child) {
    if (isset($child->b)) {
        continue;
    }
    $child->b = '';
}
// output to new file
$xml->asXML('xml2.xml');

您还可以找到包含所有数据的在线演示:

<?php
/**
 * Add element to XML when not existing in child PHP
 * @link http://stackoverflow.com/q/19562757/367456
 */
$xml = new SimpleXMLElement('<r><product><b>hello</b></product><product/><product/></r>');
foreach ($xml->children() as $child) {
    if (isset($child->b)) {
        continue;
    }
    $child->b = '';
}
$xml->asXML('php://output');

程序输出(美化):

<?xml version="1.0"?>
<r>
  <product>
    <b>hello</b>
  </product>
  <product>
    <b></b>
  </product>
  <product>
    <b></b>
  </product>
</r>