New Method to Get News using cURL

The previous method to get news has caused some problems. This new method appears to be more stable:

function shortenString($text) {
$chars = 90;
$text = $text. ' ';
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text.'…';
return $text;
}

function parseRSS($xml)
{
$cnt = count($xml->channel->item);
$start = count($xml->channel->item)-1; // 3 most recent
for($i=$start; $i<$cnt; $i++)
{
$url = $xml->channel->item[$i]->link;
$title = $xml->channel->item[$i]->title;
$desc = $xml->channel->item[$i]->description;
$date = $xml->channel->item[$i]->pubDate;

echo '<div>
<h3><a href="'.$url.'">'.$title.'</a></h3>
<p>'.str_replace('Continue reading <span>&#8594;</span>',"more",$desc).'</p>
<p>Posted on: '.date('d/m/Y', strtotime($date)).'</p>
</div>';
}
}
echo '<div id="sidebar"><h2>Latest News</h2>';
$ch = curl_init("http://www.website.com/blog/feed/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);
if(isset($doc->channel))
{
$output .= parseRSS($doc);
}
echo '</div>';

Tags: , , ,

About Keiron

Web Developer based in the UK. Click here if you want to work with me