Haber servisleri veya belirli kurumlar tarafından duyuru amaçlı yayınlanan rss servislerini çekip kendi sitenizde göstermek istiyorsanız oldukça kullanışlı bir betiktir, orjinalini dynamicdrive.com dan indirip biraz düzenledim, bayındırlık.gov.tr, haber7, anadolu ajansı gibi sitelerin rss yayınlarını çekmek için kullandım ve sizinlede paylaşayım dedim
Orjinali için;
İlk olarak aşağıda yazılı işlemleri sırayla yapınız
Aşağıdaki kodları kopyalayıp rss.php olarak kaydedin
<script src="rssticker.js" type="text/javascript">
/*********************************************** * Advanced RSS Ticker (Ajax invocation)- © Dynamic Drive DHTML code library (www.dynamicdrive.com) * This notice MUST stay intact for legal use * Visit Dynamic Drive at http://www.dynamicdrive.com/ for this script and 100s more ***********************************************/
</script>
<style type="text/css">
/*Sample CSS to style the two tickers in the demo*/
.cnnclass{ width: 190px; padding: 5px; background-color: #fff4f4; border: 0px; margin-bottom: 1em; filter:progid:DXImageTransform.Microsoft.alpha(opacity=80); /*Specify fade effect in IE. Remove if desired.*/ -moz-opacity: 0.8; /*Specify fade effect in Firefox. Remove if desired.*/ font-size:8pt; font-family:tahoma; }
.cnnclass a{ text-decoration: none; }
.bbcclass{ width: 400px; padding: 6px; background-color: lightyellow; border: 1px solid #004A00; }
.rsstitle{ /*shared class for all title elements in an RSS feed*/ font-weight: bold; }
.rssdate{ /*shared class for all date elements in an RSS feed*/ color: gray; font-size: 85%; }
.rssdescription{ /*shared class for all description elements in an RSS feed*/ }
</style>
</head> <body> <!-- Çektiğiniz haberin gösterileceği alanın uzunluğunu aşağıdan belirleyiniz --> <div style="height: 100px">
<script type="text/javascript"> //rssticker_ajax(RSS_id, cachetime, divId, divClass, delay, optionalswitch) //1) RSS_id: "Array key of RSS feed in PHP script" //2) cachetime: Time to cache the feed in minutes (0 for no cache) //3) divId: "ID of DIV to display ticker in. DIV dynamically created" //4) divClass: "Class name of this ticker, for styling purposes" //5) delay: delay between message change, in milliseconds //6) optionalswitch: "optional arbitrary" string to create additional logic in call back function
document.write("<font style=\"color:navy;font-weight:bold;\">HABER7 SON DAKİKA</font>") new rssticker_ajax("AA", 600, "cnnbox", "cnnclass", 3000, "date")
/* diğer kaynakların eklenmesi için document.write("<br />BBC News: (Title+date+description shown)") new rssticker_ajax("BBC", 1200, "ddbox", "bbcclass", 3500, "date+description") */
</script> </div>
Aşağıdaki kodları kopyalayın ve rssticker.js olarak kaydedin
// ------------------------------------------------------------------- // Advanced RSS Ticker (Ajax invocation) core file // Author: Dynamic Drive (http://www.dynamicdrive.com) // -------------------------------------------------------------------
//Relative URL syntax: var lastrssbridgeurl="lastrss/bridge.php"
//Absolute URL syntax. Uncomment below line if you wish to use an absolute reference: //var lastrssbridgeurl="http://"+window.location.hostname+"/lastrss/bridge.php"
////////////No need to edit beyond here//////////////
function createAjaxObj(){ var httprequest=false if (window.XMLHttpRequest){ // if Mozilla, Safari etc httprequest=new XMLHttpRequest() if (httprequest.overrideMimeType) httprequest.overrideMimeType('text/xml') } else if (window.ActiveXObject){ // if IE try { httprequest=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ httprequest=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return httprequest }
// ------------------------------------------------------------------- // Main RSS Ticker Object function // rssticker_ajax(RSS_id, cachetime, divId, divClass, delay, optionallogicswitch) // -------------------------------------------------------------------
function rssticker_ajax(RSS_id, cachetime, divId, divClass, delay, logicswitch){ this.RSS_id=RSS_id //Array key indicating which RSS feed to display this.cachetime=cachetime //Time to cache feed, in minutes. 0=no cache. this.tickerid=divId //ID of ticker div to display information this.delay=delay //Delay between msg change, in miliseconds. this.logicswitch=(typeof logicswitch!="undefined")? logicswitch : "" this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over ticker (and pause it if it is) this.pointer=0 this.opacitysetting=0.2 //Opacity value when reset. Internal use. this.title=[], this.link=[], this.description=[], this.pubdate=[] //Arrays to hold each component of an RSS item this.ajaxobj=createAjaxObj() document.write('<div id="'+divId+'" class="'+divClass+'" >Veri Yükleniyor...</div>') if (window.getComputedStyle) //detect if moz-opacity is defined in external CSS for specified class this.mozopacityisdefined=(window.getComputedStyle(document.getElementById(this.tickerid), "").getPropertyValue("-moz-opacity")==1)? 0 : 1 this.getAjaxcontent() }
// ------------------------------------------------------------------- // getAjaxcontent()- Makes asynchronous GET request to "bridge.php" with the supplied parameters // -------------------------------------------------------------------
rssticker_ajax.prototype.getAjaxcontent=function(){ if (this.ajaxobj){ var instanceOfTicker=this var parameters="id="+encodeURIComponent(this.RSS_id)+"&cachetime="+this.cachetime+"&bustcache="+new Date().getTime() this.ajaxobj.onreadystatechange=function(){instanceOfTicker.initialize()} this.ajaxobj.open('GET', lastrssbridgeurl+"?"+parameters, true) this.ajaxobj.send(null) } }
// ------------------------------------------------------------------- // initialize()- Initialize ticker method. // -Gets contents of RSS content and parse it using JavaScript DOM methods // -------------------------------------------------------------------
rssticker_ajax.prototype.initialize=function(){ if (this.ajaxobj.readyState == 4){ //if request of file completed if (this.ajaxobj.status==200){ //if request was successful var xmldata=this.ajaxobj.responseXML if(xmldata.getElementsByTagName("item").length==0){ //if no <item> elements found in returned content document.getElementById(this.tickerid).innerHTML="<b>Error</b> fetching remote RSS feed!<br />"+this.ajaxobj.responseText return } var instanceOfTicker=this this.feeditems=xmldata.getElementsByTagName("item") //Cycle through RSS XML object and store each peice of an item inside a corresponding array for (var i=0; i<this.feeditems.length; i++){ this.title[i]=this.feeditems[i].getElementsByTagName("title")[0].firstChild.nodeValue this.link[i]=this.feeditems[i].getElementsByTagName("link")[0].firstChild.nodeValue this.description[i]=this.feeditems[i].getElementsByTagName("description")[0].firstChild.nodeValue this.pubdate[i]=this.feeditems[i].getElementsByTagName("pubDate")[0].firstChild.nodeValue } document.getElementById(this.tickerid).onmouseover=function(){instanceOfTicker.mouseoverBol=1} document.getElementById(this.tickerid).onmouseout=function(){instanceOfTicker.mouseoverBol=0} this.rotatemsg() } } }
// ------------------------------------------------------------------- // rotatemsg()- Rotate through RSS messages and displays them // -------------------------------------------------------------------
rssticker_ajax.prototype.rotatemsg=function(){ var instanceOfTicker=this if (this.mouseoverBol==1) //if mouse is currently over ticker, do nothing (pause it) setTimeout(function(){instanceOfTicker.rotatemsg()}, 100) else{ //else, construct item, show and rotate it! var tickerDiv=document.getElementById(this.tickerid) var linktitle='<div class="rsstitle"><a href="'+this.link[this.pointer]+'">'+this.title[this.pointer]+'</a></div>' var description='<div class="rssdescription">'+this.description[this.pointer]+'</div>' var feeddate='<div class="rssdate">'+this.pubdate[this.pointer]+'</div>' if (this.logicswitch.indexOf("description")==-1) description="" if (this.logicswitch.indexOf("date")==-1) feeddate="" var tickercontent=linktitle+feeddate+description //STRING FOR FEED CONTENTS this.fadetransition("reset") //FADE EFFECT- RESET OPACITY tickerDiv.innerHTML=tickercontent this.fadetimer1=setInterval(function(){instanceOfTicker.fadetransition('up', 'fadetimer1')}, 100) //FADE EFFECT- PLAY IT this.pointer=(this.pointer<this.feeditems.length-1)? this.pointer+1 : 0 setTimeout(function(){instanceOfTicker.rotatemsg()}, this.delay) //update container every second } }
// ------------------------------------------------------------------- // fadetransition()- cross browser fade method for IE5.5+ and Mozilla/Firefox // -------------------------------------------------------------------
rssticker_ajax.prototype.fadetransition=function(fadetype, timerid){ var tickerDiv=document.getElementById(this.tickerid) if (fadetype=="reset") this.opacitysetting=0.2 if (tickerDiv.filters && tickerDiv.filters[0]){ if (typeof tickerDiv.filters[0].opacity=="number") //IE6+ tickerDiv.filters[0].opacity=this.opacitysetting*100 else //IE 5.5 tickerDiv.style.filter="alpha(opacity="+this.opacitysetting*100+")" } else if (typeof tickerDiv.style.MozOpacity!="undefined" && this.mozopacityisdefined){ tickerDiv.style.MozOpacity=this.opacitysetting } if (fadetype=="up") this.opacitysetting+=0.2 if (fadetype=="up" && this.opacitysetting>=1) clearInterval(this[timerid]) }
lastrss adında bir dosya açın ve aşağıdaki sayfaları içine yerleştirin
bridge.php
lastRSS.php
cache
(klasör, CHMOD 777 olacak)
Yukarıda belirttiğimiz sayfaları hazırlayalım Önce cache adında bir klasör oluşturalım
Aşağıdaki kodları kopyalayıp bridge.php olarak kaydedin ve lastrss klasörünün içine yerleştirin
/* ====================================================================== LastRSS bridge script- By Dynamic Drive (http://www.dynamicdrive.com) Communicates between LastRSS.php to Advanced Ajax ticker script using Ajax. Returns RSS feed in XML format Created: Feb 9th, 2006. Updated: Feb 9th, 2006 ====================================================================== */
header('Content-type: text/xml');
// include lastRSS include "lastRSS.php"; //path to lastRSS.php on your server from this script ("bridge.php")
// Create lastRSS object $rss = new lastRSS; $rss->cache_dir = 'cache'; // bu klasör Chmod 777! $rss->date_format = 'M d, Y g:i:s A'; //tarih formatı of RSS item. See PHP date() function for possible input.
// List of RSS URLs $rsslist=array( "AA" => "http://sondakika.haber7.com/sondakika.rss",
/* başka kaynak eklemek için aşağıdaki işlemin aynısı yapılır ve başta verilen isim ajax ile index e çekilir. "BBC" => "http://www.sabah.com.tr/rss/Anasayfa.xml", */
);
////Beginners don't need to configure past here////////////////////
$rssid=$_GET['id']; $rssurl=isset($rsslist[$rssid])? $rsslist[$rssid] : die("Error: Can't find requested RSS in list.");
// ------------------------------------------------------------------- // outputRSS_XML()- Outputs the "title", "link", "description", and "pubDate" elements of an RSS feed in XML format // -------------------------------------------------------------------
function outputRSS_XML($url) { global $rss; $cacheseconds=(int) $_GET["cachetime"]; //typecast "cachetime" parameter as integer (0 or greater) $rss->cache_time = $cacheseconds; if ($rs = $rss->get($url)) { echo "<?xml version=\"1.0\" encoding=\"ISO-8859-9\"?>\n<rss version=\"2.0\">\n<channel>\n"; foreach ($rs['items'] as $item) { echo "<item>\n<link>$item[link]</link>\n<title>$item[title]</title>\n<description>$item[description]</description>\n<pubDate>$item[pubDate]</pubDate>\n</item>\n\n"; } echo "</channel></rss>"; if ($rs['items_count'] <= 0) { echo "<li>Sorry, no items found in the RSS file :-(</li>"; } } else { echo "Sorry: It's not possible to reach RSS file $url\n<br />"; // you will probably hide this message in a live version } }
// ===============================================================================
outputRSS_XML($rssurl);
?>
Aşağıdaki kodları kopyalayıp lastRSS.php olarak kaydedin ve lastrss klasörünün içine yerleştirin ( Klasör ve dosya isinlerindeki büyük - küçük haflere dikkat edin!)
<?php /* ====================================================================== lastRSS 0.9.1 Simple yet powerfull PHP class to parse RSS files. by Vojtech Semecky, webmaster @ webdot . cz Latest version, features, manual and examples: http://lastrss.webdot.cz/
---------------------------------------------------------------------- LICENSE
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html ====================================================================== */
/** * lastRSS * Simple yet powerfull PHP class to parse RSS files. */ class lastRSS { // ------------------------------------------------------------------- // Public properties // ------------------------------------------------------------------- var $default_cp = 'windows-1254'; var $CDATA = 'nochange'; var $cp = ''; var $items_limit = 0; var $stripHTML = False; var $date_format = 'd M Y D - G:i';
// ------------------------------------------------------------------- // Private variables // ------------------------------------------------------------------- var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs'); var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source'); var $imagetags = array('title', 'url', 'link', 'width', 'height'); var $textinputtags = array('title', 'description', 'name', 'link');
// ------------------------------------------------------------------- // Parse RSS file and returns associative array. // ------------------------------------------------------------------- function Get ($rss_url) { // If CACHE ENABLED if ($this->cache_dir != '') { $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url); $timedif = @(time() - filemtime($cache_file)); if ($timedif < $this->cache_time) { // cached file is fresh enough, return cached array $result = unserialize(join('', file($cache_file))); // set 'cached' to 1 only if cached file is correct if ($result) $result['cached'] = 1; } else { // cached file is too old, create new $result = $this->Parse($rss_url); $serialized = serialize($result); if ($f = @fopen($cache_file, 'w')) { fwrite ($f, $serialized, strlen($serialized)); fclose($f); } if ($result) $result['cached'] = 0; } } // If CACHE DISABLED >> load and parse the file directly else { $result = $this->Parse($rss_url); if ($result) $result['cached'] = 0; } // return result return $result; } // ------------------------------------------------------------------- // Modification of preg_match(); return trimed field with index 1 // from 'classic' preg_match() array output // ------------------------------------------------------------------- function my_preg_match ($pattern, $subject) { // start regullar expression preg_match($pattern, $subject, $out);
// if there is some result... process it and return it if(isset($out[1])) { // Process CDATA (if present) if ($this->CDATA == 'content') { // Get CDATA content (without CDATA tag) $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>'')); } elseif ($this->CDATA == 'strip') { // Strip CDATA $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>'')); }
// If code page is set convert character encoding to required if ($this->cp != '') //$out[1] = $this->MyConvertEncoding($this->rsscp, $this->cp, $out[1]); $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]); // Return result return trim($out[1]); } else { // if there is NO result, return empty string return ''; } }
// ------------------------------------------------------------------- // Replace HTML entities &something; by real characters // ------------------------------------------------------------------- function unhtmlentities ($string) { // Get HTML entities table $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES); // Flip keys<==>values $trans_tbl = array_flip ($trans_tbl); // Add support for ' entity (missing in HTML_ENTITIES) $trans_tbl += array(''' => "'"); // Replace entities by values return strtr ($string, $trans_tbl); }
// ------------------------------------------------------------------- // Parse() is private method used by Get() to load and parse RSS file. // Don't use Parse() in your scripts - use Get($rss_file) instead. // ------------------------------------------------------------------- function Parse ($rss_url) { // Open and load RSS file if ($f = @fopen($rss_url, 'r')) { $rss_content = ''; while (!feof($f)) { $rss_content .= fgets($f, 4096); } fclose($f);
// Parse document encoding $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content); // if document codepage is specified, use it if ($result['encoding'] != '') { $this->rsscp = $result['encoding']; } // This is used in my_preg_match() // otherwise use the default codepage else { $this->rsscp = $this->default_cp; } // This is used in my_preg_match()
// Parse CHANNEL info preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel); foreach($this->channeltags as $channeltag) { $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]); if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty } // If date_format is specified and lastBuildDate is valid if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) { // convert lastBuildDate to specified date format $result['lastBuildDate'] = date($this->date_format, $timestamp); }
// Parse TEXTINPUT info preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo); // This a little strange regexp means: // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag) if (isset($out_textinfo[2])) { foreach($this->textinputtags as $textinputtag) { $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]); if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty } } // Parse IMAGE info preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo); if (isset($out_imageinfo[1])) { foreach($this->imagetags as $imagetag) { $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]); if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty } } // Parse ITEMS preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items); $rss_items = $items[2]; $i = 0; $result['items'] = array(); // create array even if there are no items foreach($rss_items as $rss_item) { // If number of items is lower then limit: Parse one item if ($i < $this->items_limit || $this->items_limit == 0) { foreach($this->itemtags as $itemtag) { $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item); if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty } // Strip HTML tags and other bullshit from DESCRIPTION if ($this->stripHTML && $result['items'][$i]['description']) $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description']))); // Strip HTML tags and other bullshit from TITLE if ($this->stripHTML && $result['items'][$i]['title']) $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title']))); // If date_format is specified and pubDate is valid if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) { // convert pubDate to specified date format $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp); } // Item counter $i++; } }
$result['items_count'] = $i; return $result; } else // Error in opening return False { return False; } } }
?>
Son olarak;
oluşturduğunuz dosyaları
./rss.php
./rssticker.js
./lastrss
ana dizine konulmalı
./lastrss/bridge.php
./lastrss/lastRSS.php
./lastrss/cache
lastrss klasörüne konulmalı
cache klasörü CHMOD 777 olmalıdır.
rss haber veya duyuruları sayfalarınıza
<? include('rss.php');?>
betiğini ekleyerek çekebilirsiniz
********************************************************************************************
********************************************************************************************
** **
** ksabitk@hotmail.com **
** **
********************************************************************************************
******************************************************************************************** |