2013-12-15 39 views
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>標籤?

回答

1

從另一個角度來看待它。您創建了一個新文檔,結合了您書中的所有章節。因此,創建一個書籍元素並將章節導入其中。

// 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();