dongshen7561 2014-02-11 18:59
浏览 116


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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题
  • ¥30 gradle环境下javafx项目如何使用druid连接池
  • ¥15 服务器打印水晶报表问题