Retrieving a subset of XML nodes with PHP

前端 未结 5 1732
无人及你
无人及你 2020-12-20 00:48

Using PHP, how do I get an entire subset of nodes from an XML document? I can retrieve something like:


5条回答
  •  余生分开走
    2020-12-20 01:07

    Use DOM and XPath. Xpath allows you to select nodes (and values) from an XML DOM.

    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    
    $result = '';
    foreach ($xpath->evaluate('/people/certain') as $node) {
      $result .= $dom->saveXml($node);
    }
    
    echo $result;
    

    Demo: https://eval.in/162149

    DOMDocument::saveXml() has a context argument. If provided it saves that node as XML. Much like outerXml(). PHP is able to register your own classes for the DOM nodes, too. So it is even possible to add an outerXML() function to element nodes.

    class MyDomElement extends DOMElement {
      public function outerXml() {
        return $this->ownerDocument->saveXml($this);
      }
    }
    
    class MyDomDocument extends DOMDocument {
      public function __construct($version = '1.0', $encoding = 'utf-8') {
        parent::__construct($version, $encoding);
        $this->registerNodeClass('DOMElement', 'MyDomElement');
      }
    }
    
    $dom = new MyDomDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    
    $result = '';
    foreach ($xpath->evaluate('/people/certain') as $node) {
      $result .= $node->outerXml();
    }
    
    echo $result;
    

    Demo: https://eval.in/162157

提交回复
热议问题