[英]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.