猿问

如何将 SimpleXMLElement 节点添加为子元素?

我有这个 PHP 代码。在$target_xml和$source_xml变量是SimpleXMLElement对象:


$target_body = $target_xml->children($this->namespaces['main']);

$source_body = $source_xml->children($this->namespaces['main']);


foreach ($source_body as $source_child) {

    foreach ($source_child as $p) {

        $target_body->addChild('p', $p, $this->namespace['main']);

    }

}

在$p将是这样的 XML 代码:


<w:p w:rsidR="009F3A42" w:rsidRPr="009F3A42" w:rsidRDefault="009F3A42" w:rsidP="009F3A42">

    <w:pPr>

        <w:pStyle w:val="NormlWeb"/>

        // .... here is more xml tags

    </w:pPr>

    <w:r w:rsidRPr="009F3A42">

        <w:rPr>

            <w:rFonts w:ascii="Open Sans" w:hAnsi="Open Sans" w:cs="Open Sans"/>

            <w:b/>

            <w:color w:val="000000"/>

            <w:sz w:val="21"/>

            <w:szCs w:val="21"/>

        </w:rPr>

        <w:t>Lorem ipsum dolor sit amet...</w:t>

    </w:r>

    <w:bookmarkStart w:id="0" w:name="_GoBack"/>

    <w:bookmarkEnd w:id="0"/>

</w:p>

我上面的 PHP 代码将仅将此 XML 代码添加到目标文档中:


<w:p/>

所以所有的子节点都丢失了。


如何添加具有自己的子节点的子节点?


互换的青春
浏览 262回答 2
2回答

千巷猫影

SimpleXML 适用于基本事物,但缺乏 DOMDocument 的控制(和复杂性)。将内容从一个文档复制到另一个文档时,您必须做三件事(对于 SimpleXML),首先是将其转换为 a DOMElement,然后使用importNode()withtrue作为第二个参数将其导入到目标文档中,表示进行深度复制。这只是使其可用于目标文档,而不是实际放置内容。这是使用appendChild()新导入的节点完成的...// Convert target SimpleXMLElement to DOMElement$targetImport = dom_import_simplexml($target_body);foreach ($source_body as $source_child) {&nbsp; &nbsp; foreach ($source_child as $p) {&nbsp; &nbsp; &nbsp; &nbsp; // Convert SimpleXMLElement to DOMElement&nbsp; &nbsp; &nbsp; &nbsp; $sourceImport = dom_import_simplexml($p);&nbsp; &nbsp; &nbsp; &nbsp; // Import the new node into the target document&nbsp; &nbsp; &nbsp; &nbsp; $import = $targetImport->ownerDocument->importNode($sourceImport, true);&nbsp; &nbsp; &nbsp; &nbsp; // Add the new node to the correct part of the target&nbsp; &nbsp; &nbsp; &nbsp; $targetImport->appendChild($import);&nbsp; &nbsp; }}

江户川乱折腾

该SimpleXMLElement::addChild方法只接受简单的值。但在这种情况下,您正在尝试添加另一个SimpleXMLElement对象。您可以查看建议使用 DOM 的链接https://stackoverflow.com/a/2356245/6824629这是官方的函数文档https://www.php.net/manual/en/function.dom-import-simplexml.php fordom_import_simplexml您的代码应如下所示:<?php$target_xml = new DOMDocument('1.0');$source_body = $source_xml->children($this->namespaces['main']);foreach ($source_body as $source_child) {&nbsp; &nbsp; foreach ($source_child as $p) {&nbsp; &nbsp; &nbsp; &nbsp; $dom_sxe = dom_import_simplexml($p);&nbsp; &nbsp; &nbsp; &nbsp; // don't forget to handle your errors&nbsp; &nbsp; &nbsp; &nbsp; $target_xml->appendChild($dom_sxe);&nbsp; &nbsp; }}//you get back your target xml hereecho $target_xml->saveXML();
随时随地看视频慕课网APP
我要回答