PHP DOM 将子元素附加到根元素

我正在尝试将子元素附加到预加载的根元素,如下所示


    $document = new DOMDocument('1.0', 'UTF-8');

    $document->loadXML('<books></books>');



    $content = '<books>

                   <book>

                       <athors>

                           <athor>

                               <name>John Doe</name>

                           </athor>

                       </athors>

                   </book>

               </books>';

     

    $books = new DOMDocument()


    $books->loadXML($content);


    foreach ($books as $book){

        $document->appendChild($document->importNode( $book, true ));

    }

由于某种原因,结果 xml 文档将如下所示,根元素的结束标记位于文档的开头:


   <?xml version="1.0"?>

   <books/>

         <book>

                       <athors>

                           <athor>

                               <name>John Doe</name>

                           </athor>

                       </athors>

          </book>

我希望它像下面这样:


   <?xml version="1.0"?>

   <books>

         <book>

                       <athors>

                           <athor>

                               <name>John Doe</name>

                           </athor>

                       </athors>

          </book>

   <books/>


呼如林
浏览 72回答 1
1回答

素胚勾勒不出你

您正在迭代 中根元素的子元素$books,而不是book元素。然后您将附加到 的根$document,而不是books元素。您需要深入每个节点才能找到适当的节点。<?php$document = new DOMDocument('1.0', 'UTF-8');$document->loadXML('<books></books>');$documentBooks = $document->childNodes[0];$content = '<books>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<book>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<athors>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<athor>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<name>John Doe</name>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</athor>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</athors>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</book>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</books>';&nbsp; &nbsp; &nbsp;$books = new DOMDocument();$books->loadXML($content);$bookItems = $books->childNodes[0]->childNodes;foreach ($bookItems as $book){&nbsp; &nbsp; $documentBooks->appendChild($document->importNode( $book, true ));}echo $document->saveXML();
打开App,查看更多内容
随时随地看视频慕课网APP