使用 xpath 和 PHP 的 XML:如何访问条目属性的文本值

发布于 2024-08-15 04:35:32 字数 796 浏览 6 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

复古式 2024-08-22 04:35:32

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

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";
    }
}
囚我心虐我身 2024-08-22 04:35:32

您很接近:

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

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

You were close:

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

Should be the correct XPath to get those values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文