PHP中的Xpath查询从具有特定属性值的元素进行属性

时间:2014-02-11 18:59:06

标签: php xml xpath simplexml

我真的很想知道应该简单的事情。我有一个XML源,在根目录中有25个条目。我已经在PHP中将它们作为$entry进行迭代。

以下是xml Feed中一个条目的示例:

<entry>
      <id>tag:blogger.com,1999:blog-7691515427771054332.post-4593968385603307594</id>
      <published>2014-02-10T06:33:00.000-05:00</published>
      <updated>2014-02-10T06:40:34.678-05:00</updated>
      <category scheme="http://www.blogger.com/atom/ns#" term="Aurin" />
      <category scheme="http://www.blogger.com/atom/ns#" term="fan art" />
      <category scheme="http://www.blogger.com/atom/ns#" term="Fred-H" />
      <category scheme="http://www.blogger.com/atom/ns#" term="spellslinger" />
      <category scheme="http://www.blogger.com/atom/ns#" 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="http://www.blogger.com/feeds/7691515427771054332/posts/default/4593968385603307594" />
      <link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7691515427771054332/posts/default/4593968385603307594" />
      <link rel="alternate" type="text/html" href="http://www.wildstarfans.net/2014/02/fan-art-showcase-shes-gunnin-for-trouble.html" title="Fan Art Showcase: She's gunnin' for trouble!" />
      <author>
         <name>Name Removed</name>
         <uri>URL removed</uri>
         <email>noreply@blogger.com</email>
         <gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh3.googleusercontent.com/-ow-dvUDbNxI/AAAAAAAAAAI/AAAAAAAABTY/MhrybgagMv0/s512-c/photo.jpg" />
      </author>
      <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-Ifp6awhDJuU/UWQEUl8nhUI/AAAAAAAABss/BSZ_YYM1U38/s72-c/fan-art-header.png" height="72" width="72" />
</entry>

我想获得第三个链接的href,其中rel设置为alternate。替代链接并不总是第三个。我知道如何通过SimpleXML来实现这一点,但我想了解xpath,因为通过simpleXML它更复杂,我希望我更接近理解复杂的xpath查询。

我得到的PHP对我来说最有意义的是:

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

我根据我找到的信息尝试了多个查询,但它们都没有产生任何结果。以下是我尝试的查询列表:

  • $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 个答案:

答案 0 :(得分:2)

从原始问题的the chat conversation开始,我必须注册命名空间。最后我使用了this website,结果证明是这样的:

$feed = new DOMDocument();
$feed->load("http://www.wildstarfans.net/feeds/posts/default");

$xpath = new DOMXPath($feed);
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');

foreach ($xpath->evaluate('//atom:entry') as $entry) {

    $href = $xpath->evaluate('string(atom:link[@rel="alternate"]/@href)', $entry);

}

积分转到ThWWrikken。希望我能为你们提供SO点数。

答案 1 :(得分:0)

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