In PHP, how can I get the Outer XML from a DOMNode?

后端 未结 3 694
名媛妹妹
名媛妹妹 2020-12-06 10:44

If you have DOMNode in PHP, how can you get the outer xml (i.e. the all of the XML that is inside this element plus the element itself)?

For example, lets say this i

相关标签:
3条回答
  • 2020-12-06 11:10

    After an hour spent, I came up with this (it seems the best solution)

    $node->ownerDocument->saveXml($node);
    
    0 讨论(0)
  • 2020-12-06 11:29

    You could try something like:

    function getInnerXml(DomNode $node){
      $xml = '';
      foreach($node->childNodes as $childNode){
        $xml .= $node->ownerDocument->saveXml($childNode);
      }
      return $xml;
    }
    
    0 讨论(0)
  • 2020-12-06 11:30

    You need a DOMDocument:

    // If you don't have a document already:
    $doc = new DOMDocument('1.0', 'UTF-8');
    
    echo $doc->saveXML($node); // where $node is your DOMNode
    

    Check DOMDocument::saveXML in the docs for more info.

    When you pass a DOMNode to saveXML() you get back only the contents of that node not the whole document.

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