我正在解析RSS提要以获取原始数据并进行操作。
在WordPress RSS Feed上。我可以通过迭代SimpleXMLElement
找到标题,链接,描述并发布帖子。节点位于:
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;
分别
问题是$description
里面有<p>
个问题。一个对我没用的;第二个。
那么如何将$description
仅分配给描述的第一个<p>
?
简单地$xml->channel->item[$i]->description->p[0]
赢得了工作。这会导致内部服务器错误。
我的整个代码如下:
<?php
$html = "";
$url = "http://sntsh.com/posts/feed/";
$xml = simplexml_load_file($url);
for($i = 0; $i < 10; $i++){
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description->children();
$pubDate = $xml->channel->item[$i]->pubDate;
$html .= "<a href='$link'><h3>$title</h3></a>";
$html .= "$description";
$html .= "<br />$pubDate";
}
echo $html;
答案 0 :(得分:0)
您可以使用children()
方法获取元素的子元素。如果你可以保证第一个孩子永远是你需要的元素,你可以这样使用它:
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description->children();
$pubDate = $xml->channel->item[$i]->pubDate;
children()
函数旨在以迭代方式使用,每次调用它时,它都会将下一个子项作为SimpleXMLElement
返回。 http://php.net/manual/en/simplexmlelement.children.php
修改强>
似乎问题的原因是<![CDATA[
]]>
标记。它们导致SimpleXMLElement为空。剥离他们修复它:
$html = '';
$src = file_get_contents('http://sntsh.com/posts/feed/');
$search = ["<![CDATA[","]]>"];
$replace = array('','');
$data = str_replace($search,$replace,$src);
$xml = simplexml_load_string($data);
for($i = 0; $i < count($xml->channel->item); $i++)
{
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description->children();
// Or
// $description = $xml->channel->item[$i]->description->p[0];
$pubDate = $xml->channel->item[$i]->pubDate;
$html .= "<a href='$link'><h3>$title</h3></a>";
$html .= trim($description).'...';
$html .= "<br />$pubDate";
}
echo $html;