【发布时间】:2014-02-11 18:59:05
【问题描述】:
我真的在低头思考应该是简单的事情。我有一个根中有 25 个条目的 XML 提要。我已经在 PHP 中将它们迭代为 $entry。
这是 xml 提要中的一个条目的示例:
<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'];
【问题讨论】:
-
属性不是
text()节点,所以(string)$entry->xpath('link[@rel="alternate"]/@href')[0]对我有用。[0]requires php >= 5.4顺便说一句。 -
顺便说一句:如果
link没有找到任何东西......你确定你在entry节点中吗? -
我正在使用 PHP 5.3。
link确实返回一个空数组。但是我可以通过simpleXML 和$entry->title 获得标题。所以我一定在entry对吧? -
嗯,
$entry[0]->query()是做什么的? -
它返回
Call to undefined method SimpleXMLElement::query()。当我print_r($entry[0])(或没有[0])时,它返回条目:wildupdates.com/test/test.php