Retrieving a subset of XML nodes with PHP

前端 未结 5 1731
无人及你
无人及你 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:10

    The answer would be to use XPath.

    $people = simplexml_load_string(
        '
        
          
            Jane Doe
            21
          
          
            John Smith
            34
          
        '
    );
    
    // get all  nodes
    $people->xpath('//certain');
    
    // get all  nodes whose  is "John Smith"
    print_r($people->xpath('//certain[name = "John Smith"]'));
    
    // get all  nodes whose  child's value is greater than 21
    print_r($people->xpath('//certain[age > 21]'));
    

    Take 2

    So apparently you want to copy some nodes from a document into another document? SimpleXML doesn't support that. DOM has methods for that but they're kind of annoying to use. Which one are you using? Here's what I use: SimpleDOM. In fact, it's really SimpleXML augmented with DOM's methods.

    include 'SimpleDOM.php';
    $results = simpledom_load_string('');
    
    foreach ($people->xpath('//certain') as $certain)
    {
        $results->appendChild($certain);
    }
    

    That routine finds all node via XPath, then appends them to the new document.

提交回复
热议问题