具有xpath和PHP的XML:如何访问条目属性的文本值 [英] XML with xpath and PHP: How to access the text value of an attribute of an entry

查看:77
本文介绍了具有xpath和PHP的XML:如何访问条目属性的文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

我也尝试过各种排列,但没有运气.

I've tried all kinds of permutations, too but no luck.

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

我得到的结果是".有人可以解释我在做什么错吗?

The result I get is "". Can someone explain what I'm doing wrong?

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

Can someone please help me out? I've been at this for hours...

推荐答案

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

xpath() returns an array, you have to select the first element of that array, at index 0. Attention: if there's no match, it may return an empty array. Therefore, you should add an if (isset($xpath[0])) clause, just in case.

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

    if (isset($xpath[0]))
    {
        echo $xpath[0], "\n";
    }
}

这篇关于具有xpath和PHP的XML:如何访问条目属性的文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆