<?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>
当子元素&lt; B>缺少,我想将其添加到XML文件。所以&lt;产品&gt;像这样结束。没有数据必须添加,只是元素。
<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) {}
答案 0 :(得分:0)
这绝对是可能的。以下是如何执行此操作的示例(假设您不担心子元素发生的顺序):
$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');
您还可以找到包含所有数据的an online Demo:
<?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>