0
我試圖將文件夾「files」中的xml-documents合併到一個DOMDocument中,並創建一個目錄。將幾個XML文檔與PHP相結合使用
的文件具有以下結構:
<chapter title="This is first chapter">
<section title="This is the first section">
<paragraph title="This is the first paragraph">This is the paragraph content</paragraph>
</section>
</chapter>
下面的代碼被用於合併XML的文件:
foreach(glob("files/*xml") as $filename) {
$count++;
if ($count == 1)
{
$first = new DOMDocument("1.0", 'UTF-8');
$first->formatOutput = true;
$first->load($filename);
$xml = new DOMDocument("1.0", 'UTF-8');
$xml->formatOutput = true;
}
else {
$second = new DOMDocument("1.0", 'UTF-8');
$second->formatOutput = true;
$second->load($filename);
$second = $second->documentElement;
foreach($second->childNodes as $node)
{
$importNode = $first->importNode($node,TRUE);
$first->documentElement->appendChild($importNode);
}
$first->saveXML();
$xml->appendChild($xml->importNode($first->documentElement,true));
}
}
print $xml->saveXML();
一切似乎工作確定,除了與<chapter>
-elements問題。這兩個文檔時(比方說,我在我的問題一開始提出的XML的兩個相同的版本)被合併發生了什麼:
<chapter title="This is first chapter">
<section title="This is the first section">
<paragraph title="This is the first paragraph">This is the paragraph content</paragraph>
</section>
<chapter title="This is second chapter">
<section title="This is the first section">
<paragraph title="This is the first paragraph">This is the paragraph content</paragraph>
</section>
</chapter>
</chapter>
我認爲這個問題的原因,是沒有根元素爲合併的文件。那麼,有沒有一種方法可以爲合併的XML添加<doc>
標籤?