将几个XML文档与PHP组合在一起

时间:2013-12-15 18:23:22

标签: php xml xslt

我正在尝试将文件夹“files”中的xml文档合并到一个DOMDocument中,并创建一个目录。

文件具有以下结构:

    <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> - 元素的问题外,一切似乎都运行正常。当合并两个文档(假设在我的问题开头提出的两个相同版本的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>标记或其他内容?

1 个答案:

答案 0 :(得分:1)

从另一个观点来看待它。您可以创建一个新文档,其中包含您书籍的所有章节。因此,创建一个book元素并将章节导入其中。

// create a new document
$dom = new DOMDocument();
// and add the root element
$dom->appendChild($dom->createElement('book'));

// for each document/xml to add
foreach ($chapters as $chapter) {
  // create a dom
  $addDom = new DOMDocument();
  // load the chapter
  $addDom->load($chapter);
  // if here is a root node in the loaded xml
  if ($addDom->documentElement) {
    // append to the result dom
    $dom->documentElement->appendChild(
      // after importing the document element to the result dom
      $dom->importNode($addDom->documentElement, TRUE)
    );
  }
}

echo $dom->saveXml();