[英]PHP parse xml and return first of child type in node
我正在使用 cURL 从博客中获取一些 XML。 我想遍历 XML 和输出列表项,这些列表项由环绕标题 IE <li><a href="link">Title</a></li>
的链接组成,这很简单。 问题是每个<entry>
节点中有 3 个<links>
。
第一个是正确的,其他两个有不正确的目录结构和散列,单击时不会打开帖子。 目前我只是使用str_replace
修剪已知的添加目录。 如果添加的目录“/feed/atom”发生变化,这在我的情况下不起作用,所以这不是一个好的解决方案。 我想做一些类似 $link[0] 的事情来只返回第一个链接。
简化返回的 xml
<entry>
<author>
<name>Name</name>
<uri>http://www.url.com</uri>
</author>
<title>Title</title>
<link href="http://www.url1.com" />
<link href="http://www.url2.com#comments" />
<link href="http://www.url3.com/feed/atom/" />
</entry>
我只需要第一个,在这种情况下<link href="http://www.url1.com" />
str_replace 现在在行动
<?php
function download_page($path){
//cURL stuff, all good
}
$sXML = download_page('http://example.org/feed/atom/');
$oXML = new SimpleXMLElement($sXML);
$items = $oXML->entry;
$i = 0;
foreach($items as $item) {
$title = $item->title;
$link = $item->link;
//$link = $item->link[0] or {0} neither works. Want the first one in the <entry> node
echo '<li>';
foreach($link as $links) {
$loc = $links['href'];
$href = str_replace("/feed/atom/", "", $loc);
echo "<a href=\"$href\" target=\"_blank\">";
}
echo $title;
echo "</a>";;
echo "</li>";
if(++$i == 3) break;
}
?>
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$xml = download_page('http://foo.com/tradeblog/feed/atom/');
function getHref($__xml){
$xml = new SimpleXMLElement($__xml);
foreach($xml as $node){
foreach($node->attributes() as $prop => $val){
if($prop === 'href'){
$p = strrpos($val, '/');
$val = substr($val, $p);
return $val;
}
}
}
}
$link = getHref($xml);
echo $link;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.