如何使用 PHP 从 XML“链接”标签中提取“href”属性?

Posted

技术标签:

【中文标题】如何使用 PHP 从 XML“链接”标签中提取“href”属性?【英文标题】:How do I extract the "href" attribute from an XML "link" tag using PHP? 【发布时间】:2011-05-21 18:01:13 【问题描述】:

我很困惑如何使用我的 php 解析脚本从这段 XML 中的“链接”标签中提取“href”属性。如果它有帮助,我会尝试从 GetSatisfaction API 提要中提取特定帖子的 URL。

以下是 XML 文件中的一个节点示例:

<entry>
  <link rel="something" href="http://...url_I_need" type="text/html"/>

  <title type="html">...title here...</title>
  <content type="html">
  ...content here...
  </content>
</entry>

这是我的 PHP XML 解析脚本的数据收集部分:

$doc = new DOMDocument();
$doc->load('http://api.getsatisfaction.com/companies/issuetrak/topics?sort=recently_active&limit=7');
$arrFeeds = array();
foreach ($doc->getElementsByTagName('entry') as $node) 
 $title = $node->getElementsByTagName('title')->item(0)->nodeValue;
 //I need to just store the link->href value to $link below
 //$link = ???;

关于如何提取“href”属性有什么建议吗?

谢谢!

【问题讨论】:

当您想要&lt;link&gt; 的属性时,为什么要使用getElementsByTagName('title') 【参考方案1】:

我认为你可以使用:

$link = $node->attributes['href'];

但我更喜欢使用 simpleXml;

http://www.php.net/simpleXml

【讨论】:

我认为 SimpleXML 使用自制的 XML 解析器,而不是像 libxml 这样的通用库。我觉得使用它很不安全。 我使用 getAttribute() 而不是 attributes()...我得到了所有错误。你帮助了我:D 谢谢【参考方案2】:

DOMElement::getAttribute 呢?

$href = $node->getElementsByTagName('link')->item(0)->getAttribute('href');

【讨论】:

以上是关于如何使用 PHP 从 XML“链接”标签中提取“href”属性?的主要内容,如果未能解决你的问题,请参考以下文章