How to import XML string in a php DOMDocument

前端 未结 2 1513
梦毁少年i
梦毁少年i 2020-12-09 13:32

For exemple, i create a DOMDocument like that :

createDocumen         


        
2条回答
  •  庸人自扰
    2020-12-09 14:09

    You can use a DomDocumentFragment for this:

    $fragment = $document->createDocumentFragment();
    $fragment->appendXml($xhtml);
    $elementBody->appendChild($fragment);
    

    That's all there is to it...

    Edit: Well, if you must have xhtml (instead of valid xml), you could do this dirty workaround:

    function xhtmlToDomNode($xhtml) {
        $dom = new DomDocument();
        $dom->loadHtml(''.$xhtml.'');
        $fragment = $dom->createDocumentFragment();
        $body = $dom->getElementByTagName('body')->item(0);
        foreach ($body->childNodes as $child) {
            $fragment->appendChild($child);
        }
        return $fragment;
    }
    

    usage:

    $fragment = xhtmlToDomNode($xhtml);
    $document->importNode($fragment, true);
    $elementBody->appendChild($fragment);
    

提交回复
热议问题