Parsing RSS Menggunakan 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[]  = "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[]  = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    $headers[]  = "Accept-Language:en-us,en;q=0.5";
    $headers[]  = "Accept-Encoding:gzip,deflate";
    $headers[]  = "Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $headers[]  = "Keep-Alive:115";
    $headers[]  = "Connection:keep-alive";
    $headers[]  = "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

Published by

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.

Code is my cookies. ~ Jev
Before you read or leave a comment, please take a couple minutes to read our Copyright & Disclaimer notice.

Tinggalkan Komentar