simplexml and xpath, read sibling

前端 未结 2 1429
遥遥无期
遥遥无期 2021-01-27 12:15

I have the following XML file :




    
        [...]
             


        
相关标签:
2条回答
  • 2021-01-27 12:50
    $xpath = './/wp:meta_key[text()="_yoast_wpseo_title"]/following-sibling::wp:meta_value[1]/text()';
    $items = $xml->channel->item;
    foreach( $items as $item ) {
      $result = $item->xpath($xpath);
      print "$result[0]\n";
    }
    
    // => item-1-title
    // => item-2-title
    

    Explanation of the XPath expression:

    .                               - from the current node...
    //wp:meta_key                   - get all descendant wp:meta_key nodes
    [text()="_yoast_wpseo_title"]   - whose text content is _yoast_wpseo_title
    /following-sibling::            - then get the siblings that come after this
    wp:meta_value[1]                - with tag wp:meta_value; only take the first
    /text()                         - and read its text
    
    0 讨论(0)
  • 2021-01-27 13:02

    This solution includes reference to the Wordpress XML namespace:

    $doc = new SimpleXmlElement($xml);
    $doc->registerXPathNamespace ('wp', 'http://wordpress.org/export/1.0/');
    
    $wp_meta_title = $doc->xpath("//wp:postmeta[wp:meta_key = '_yoast_wpseo_title']/wp:meta_value");
    
    foreach ($wp_meta_title as $title) {
        echo (string)$title . "\n";
    }
    

    result:

    item-1-title
    item-2-title
    

    See http://ideone.com/qjOfIW

    The path //wp:postmeta[wp:meta_key = '_yoast_wpseo_title']/wp:meta_value is pretty straight-forward, I don't think it needs special explanation.

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