2014-02-11 18:59
浏览 113


I'm truly bending my head over something that should be way to simple. I have an XML feed with 25 entries in the root. I'm already iterating them as $entry in PHP.

Here is an example of one entry in the xml feed:

      <category scheme="" term="Aurin" />
      <category scheme="" term="fan art" />
      <category scheme="" term="Fred-H" />
      <category scheme="" term="spellslinger" />
      <category scheme="" term="wildstar" />
      <title type="text">Fan Art Showcase: She's gunnin' for trouble!</title>
      <content type="html">Some random content</content>
      <link rel="edit" type="application/atom+xml" href="" />
      <link rel="self" type="application/atom+xml" href="" />
      <link rel="alternate" type="text/html" href="" title="Fan Art Showcase: She's gunnin' for trouble!" />
         <name>Name Removed</name>
         <uri>URL removed</uri>
         <gd:image rel="" width="32" height="32" src="//" />
      <media:thumbnail xmlns:media="" url="" height="72" width="72" />

I want to get the href of the third link with rel set to alternate. The alternate link isn't always the third one. I know how to do this through SimpleXML, but I want to get to know xpath for this, because through simpleXML it's more complicated and with this I hope I'm one step closer to understanding complex xpath queries.

The PHP I got that makes the most sense to me is:

$href = $entry->xpath('link[@rel="alternate"]/@href');

I tried multiple queries based on the information I found, but they all resulted in nothing. Here is a list of the queries I tried:

  • $href = $entry->xpath('link[@rel="alternate"]/@href/text()');
  • $href = $entry->xpath('link[@rel="alternate"]')->getAttributes()->href;
  • $href = $entry->xpath('*[@rel="alternate"]'); $href = $href['href'];
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douliaodan2738 2014-02-11 21:12

    As it turns out from the chat conversation from my original question I had to register the namespace. In the end I used this website and the code turned out to be like this:

    $feed = new DOMDocument();
    $xpath = new DOMXPath($feed);
    $xpath->registerNamespace('atom', '');
    foreach ($xpath->evaluate('//atom:entry') as $entry) {
        $href = $xpath->evaluate('string(atom:link[@rel="alternate"]/@href)', $entry);

    Credits go to ThW and Wrikken. Wish I could give you guys SO points for this.

    解决 无用
    打赏 举报
  • donglin6659 2014-02-11 19:22
    $href = $entry->xpath('link[@rel="alternate"]');
    $href = (string) $href[0]->attributes()->href;
    解决 无用
    打赏 举报

相关推荐 更多相似问题