【问题标题】:XML with xpath and PHP: How to access the text value of an attribute of an entry带有 xpath 和 PHP 的 XML:如何访问条目属性的文本值
【发布时间】:2009-12-16 04:14:14
【问题描述】:

xml:

<entry>
  <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://picasaweb.google.com/data/feed/api/user/xy/albumid/531885671007533108" /> 
  <link rel="alternate" type="text/html" href="http://picasaweb.google.com/xy/Cooking" /> 
  <link rel="self" type="application/atom+xml" href="http://picasaweb.google.com/data/entry/api/user/xy/albumid/531885671007533108" /> 
</entry>

这是我尝试过的:

foreach($xml->entry as $feed) {
 $album_url = $feed->xpath("./link[@rel='alternate']/@href");
 echo $album_url;
}

我也尝试过各种排列方式,但都没有成功。

预期结果为http://picasaweb.google.com/xy/Cooking

我得到的结果是“”。有人可以解释我做错了什么吗?

有人可以帮帮我吗?我已经在这里呆了好几个小时了……

【问题讨论】:

    标签: php xml xpath simplexml


    【解决方案1】:

    xpath() 返回一个数组,你必须选择该数组的第一个元素,索引为 0。注意:如果没有匹配,它可能返回一个空数组。因此,您应该添加一个if (isset($xpath[0])) 子句,以防万一。

    foreach ($xml->entry as $entry)
    {
        $xpath = $entry->xpath('./link[@rel="alternate"]/@href');
    
        if (isset($xpath[0]))
        {
            echo $xpath[0], "\n";
        }
    }
    

    【讨论】:

      【解决方案2】:

      你很亲密:

      ./link[@rel='alternate']/@href
      

      应该是获取这些值的正确 XPath。

      【讨论】:

      • 嗨,Jacob,感谢您的回答...我尝试使用上述输入,但它仍然没有返回任何值。
      • 乔什·戴维斯的回答是正确的; xpath 返回多个值。你可能只是取回一个数组。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多