XML node with Mixed Content using PHP DOM

前端 未结 1 848
醉梦人生
醉梦人生 2021-01-03 14:12

Is there a way to create a node that has mixed XML content in it with the PHP DOM?

相关标签:
1条回答
  • 2021-01-03 14:49

    If I understood you correctly you want something similar to innerHTML in JavaScript. There is a solution to that:

    $xmlString = 'some <b>mixed</b> content';
    
    $dom = new DOMDocument;
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML($xmlString);
    $dom->appendChild($fragment);
    // done
    

    To sumarize. What you need is:

    • DOMDocument::createDocumentFragment()
    • DOMDocumentFragment::appendXML()

    Although you didn't asked about it I'll tell you how to get the string representation of a DOM node as opposed to the whole DOM document:

    // for a DOMDocument you have
    $dom->save($file);
    $string = $dom->saveXML();
    
    $dom->saveHTML();
    $string = $dom->saveHTMLFile($file);
    
    // For a DOMElement you have
    $node = $dom->getElementById('some-id');
    
    $string = $node->C14N();
    $node->C14NFile($file);
    

    Those two methods are currently not documented.

    0 讨论(0)
提交回复
热议问题