Parsing RSS Menggunakan Curl dan SimpleXmlElement

Curl dan fungsi SimpleXmlElement untuk melakukan parsing file format RSS atau xml.

Curl dan SimpleXmlElement

Kali ini kita coba menggunakan Curl dan fungsi SimpleXmlElement untuk melakukan parsing file format RSS atau xml. Sebelumnya beberapa fungsi parsing seperti simplexml_load_file juga berfungsi untuk parsing RSS.

Berikut ini contoh kode PHP Curl dan SimpleXmlElement yang digabung untuk parsing RSS mesin pencari Bing.

<?php
// Fungsi Curl
function curl($url){

    $headers&#91;&#93;  = "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
    $headers&#91;&#93;  = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $headers&#91;&#93;  = "Accept-Language:en-us,en;q=0.5";
    $headers&#91;&#93;  = "Accept-Encoding:gzip,deflate";
    $headers&#91;&#93;  = "Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $headers&#91;&#93;  = "Keep-Alive:115";
    $headers&#91;&#93;  = "Connection:keep-alive";
    $headers&#91;&#93;  = "Cache-Control:max-age=0";

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_MAXREDIRS, 2);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_ENCODING, "gzip");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

$rssnull = curl('http://www.bing.com/search?q=melissa+joan+hart&count=10&format=rss');

//Fungsi SimpleXmlElement
$doc = new SimpleXmlElement($rssnull, LIBXML_NOCDATA);

function parseRSS($doc)
{
    echo "<strong>".$doc->channel->title."</strong><br/>";
    $cnt = count($doc->channel->item);
    for($i=0; $i<$cnt; $i++)
    {
	$url 	= $doc->channel->item[$i]->link;
	$title 	= $doc->channel->item[$i]->title;
	$desc = $doc->channel->item[$i]->description;
 	echo '<a href="'.$url.'">'.$title.'</a><br/>'.$desc.'<br/>';
    }
}
parseRSS($doc);
?>

Keterangan:

  • $doc->channel->title: Menampilkan kata kunci
  • $url = $doc->channel->item[$i]->link;: Menampilkan tautan/link
  • $title = $doc->channel->item[$i]->title;: Menampilkan judul/title
  • $desc = $doc->channel->item[$i]->description;: Menampilkan deskripsi

Author: Jevuska

Rachmanuddin Chair Yahya a.k.a Jevuska is the founder of Jevuska.Com, a qualified web about offering medical articles, blogging, tips, and tutorial of WordPress. Having written for Jevuska since 2007.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use tag [php] to add code, e.g. [php]<?php echo $var; ?>[/php]