使用 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;
}
我也尝试过各种排列,但没有运气。
预期结果为 http://picasaweb.google.com/xy/Cooking
我得到的结果是“”。有人可以解释我做错了什么吗?
有人可以帮我吗?我已经在这几个小时了...
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>
Here's what I've tried:
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.
Expected result would be 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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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 anif (isset($xpath[0]))
clause, just in case.您很接近:
应该是获取这些值的正确 XPath。
You were close:
Should be the correct XPath to get those values.