How to import XML string in a php DOMDocument

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

For exemple, i create a DOMDocument like that :

createDocumen         


        
2条回答
  •  春和景丽
    2020-12-09 14:00

    The problem is DOM does not know that it should consider the XHTML DTD unless you validated the document against it. Unless you do that, DOM doesnt know any entities defined in the DTD, nor any other rules in it. Fortunately, we sorted out how to do the validation in that other question, so armed with that knowledge you can do

    $document->validate(); // anywhere before importing the other DOM
    

    And then import with

    $fragment = $document->createDocumentFragment();
    $fragment->appendXML('

    Hello

    Hello World

    '); $document->getElementsByTagName('body')->item(0)->appendChild($fragment); $document->formatOutput = TRUE; echo $document->saveXml();

    outputs:

    
    
    
      
        
        My bweb page
      
      
        

    Hello

    Hello World

    The other way to import XML into another DOM is to use

    $one = new DOMDocument;
    $two = new DOMDocument;
    $one->loadXml('one');
    $two->loadXml('two');
    $bar = $two->documentElement->firstChild; // we want to import the bar tree
    $one->documentElement->appendChild($one->importNode($bar, TRUE));
    echo $one->saveXml();
    

    outputs:

    
    onetwo
    

    However, this cannot work with

    Hello

    Hello World

    because when you load a document into DOM, DOM will overwrite everything you told it before about the document. Thus, when using load, libxml (and thus SimpleXml, DOM and XMLReader) does (do) not know you mean XHTML. And it does not know any entities defined in it and will fuzz about them instead. But even if the string would not contain the entity, it is not valid XML, because it lacks a root node. That's why you use the fragment.

提交回复
热议问题