Benutzer-Werkzeuge

Webseiten-Werkzeuge


webdev:stuff:xml-rss-feeds-mit-php-und-yql-beziehen

XML / Rss Feeds mit PHP und der YQL Api beziehen

Die Beispiel-Klasse, nimmt eine beliebige YQL-Query auf und liefert das Ergbenis als Array - oder Simple-XML Objekt zurück.

Benötigt: PHP5.x + CURL

Siehe auch

Codebeispiel

class.yql.php
class yql{
 
    private $formats = array("json","xml");
    private $url = "http://query.yahooapis.com/v1/public/yql?q=%s&format=%s";
 
    public $query;
    public $format;
 
    public function setQuery($q){
        $this->query = urlencode($q);
    }
 
    public function fetchUrl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
        if(!($output = curl_exec($ch))):
            throw new Exception("CURL ERROR: ".curl_error($ch));
        endif;
        curl_close($ch);
        return $output;
    }
 
    public function setFormat($f="json"){
        if(in_array($f,$this->formats)){
            $this->format = $f;
        }else{
            $this->format = "json";
        }
 
    }
 
    public function getQuery(){
        $url = sprintf($this->url,$this->query,$this->format);
        return ($this->format=="json")
                //array object
                ? json_decode($this->fetchUrl($url))->query
                //simplexml object
                : simplexml_load_string($this->fetchUrl($url)); 
    }
 
}

Oder mit einem Cache zum Beispiel:

define("yql_temp","temp/");
define("yql_temp_time",3600);
 
 $fileName = yql_temp.md5($url).".xml";
        if(is_file($fileName)){
            $modDate = filemtime($fileName);
            if((time() - $modDate) < yql_temp_time){
                print "<!-- last yql-query: ".date("d.m.Y H:i:s",$modDate)." | Next query: ".date("d.m.Y H:i:s",$modDate+3600)." !-->".PHP_EOL;
                return file_get_contents($fileName);
            }
        }

Anwendungsbeispiel

$feeds = array();
 
array_push($feeds,"'http://datenfahrt.de/wiki/feed.php'");
array_push($feeds,"'http://feeds.feedburner.com/haikohall-podcasts'");
 
$y = new yql();
 
 
$query = sprintf("
                 SELECT title,pubDate,link,description,enclosure
                 FROM rss WHERE url IN (%s) |
                 sort(field='pubDate',descending='true')
                 ",implode(",",$feeds)
                 );
 
$y->setQuery($query);
 
try{
    $xml = $y->getQuery();
}catch(Exception $e){
    print "<h2>Error: ".$e;
    exit();
}
 
 
print_r($xml);

Ergebnis

Beispielanwendung

Die Startseite von Datenfahrt

<?php
define("yql_temp","temp/");
define("yql_temp_time",3600);
 
class yql{
 
    private $formats = array("json","xml");
    private $url = "http://query.yahooapis.com/v1/public/yql?q=%s&format=%s";
 
    public $query;
    public $format;
 
 
    public function setQuery($q){
        $this->query = urlencode($q);
    }
 
 
    public function fetchUrl($url){
        $fileName = yql_temp.md5($url).".xml";
        if(is_file($fileName)){
            $modDate = filemtime($fileName);
            if((time() - $modDate) < yql_temp_time){
                print "<!-- last yql-query: ".date("d.m.Y H:i:s",$modDate)." | Next query: ".date("d.m.Y H:i:s",$modDate+3600)." !-->".PHP_EOL;
                return file_get_contents($fileName);
            }
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(!($output = curl_exec($ch))):
            throw new Exception("CURL ERROR: ".curl_error($ch));
        endif;
        curl_close($ch);
        file_put_contents($fileName,$output);
        return $output;
    }
 
    public function setFormat($f="json"){
        if(in_array($f,$this->formats)){
            $this->format = $f;
        }else{
            $this->format = "json";
        }
 
    }
 
    public function getQuery(){
        $url = sprintf($this->url,$this->query,$this->format);
        return ($this->format=="json")
                //array object
                ? json_decode($this->fetchUrl($url))->query
                //simplexml object
                : simplexml_load_string($this->fetchUrl($url)); 
    }
 
}
 
$feeds = array();
 
array_push($feeds,"'http://datenfahrt.de/wiki/feed.php'");
array_push($feeds,"'http://datenfahrt.de/sunny/rss.php?l=10'");
array_push($feeds,"'http://feeds.feedburner.com/MatrjoschkaPodcast'");
array_push($feeds,"'http://feeds.feedburner.com/haikohall-podcasts'");
array_push($feeds,"'https://picasaweb.google.com/data/feed/base/user/haiko.hall?alt=rss&kind=album&hl=de'");
 
$y = new yql();
 
$y->setQuery("
             SELECT title,pubDate,link,description,enclosure FROM rss WHERE url IN
             (".implode(",",$feeds).") | sort(field='pubDate',descending='true')"
             );
 
try{
    $xml = $y->getQuery();
}catch(Exception $e){
    print "<h2>Error: ".$e;
    exit();
}
 
?>
<html lang="de">
    <head>
        <title>space</title>
        <link href="basic.css" type="text/css" rel='stylesheet'/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="main.js"></script>
        <meta charset="utf-8" />
    </head>
 
    <body>
 
    <h1>Datenfahrt.de</h1>
 
    <div>
        <div style="float:left">
            <a href="./wiki">Wiki</a> | <a href="./wiki/blog">Blog</a> | <a title="einen newsfeed aus mehreren quellen mit php +  yql" href="http://datenfahrt.de/wiki/webdev/stuff/xml-rss-feeds-mit-php-und-yql-beziehen">Diese Seite..</a> | <a target="_blank" href="http://datenfahrt.de/wiki/about">Impressum</a>
        </div>
        <div style="float:right">
            Target: <input type="checkbox" id="target"> Blank    
        </div>
    </div>
 
    <div style="clear: both; margin-top:50px;">
        <h2>recent posts</h2>
            <? foreach ( $xml->results->item as $item): ?>
                <div class="item">
                    <div class="date">
                    <?=$item->pubDate;?>
                    </div>
                    <div class="title">
                      <a href="<?=$item->link;?>"><?=$item->title;?></a>
                    </div>
 
                    <div class="description">
                        <?=$item->description;?>
                    </div>
                </div>
            <? endforeach; ?>
    </div>
 
 
    <!-- Piwik --> 
    <script type="text/javascript">
        var pkBaseURL = (("https:" == document.location.protocol) ? "https://datenfahrt.de/stats/" : "http://datenfahrt.de/stats/");
        document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
 
    <script type="text/javascript">
    try {
        var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
        piwikTracker.trackPageView();
        piwikTracker.enableLinkTracking();
    } catch( err ) {}
    </script>
 
    <noscript>
        <p>
            <img src="http://datenfahrt.de/stats/piwik.php?idsite=1" style="border:0" alt="" />
        </p>
    </noscript>
    <!-- End Piwik Tracking Tag -->
 
    </body>
</html>
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
*/
function prettyDate(date){
    var diff = (((new Date()).getTime() - date.getTime()) / 1000);
    var day_diff = Math.floor(diff / 86400);
    return day_diff == 0 && (
          	diff < 60 && "just now" ||
            	diff < 120 && "1 minute ago" ||
            	diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            	diff < 7200 && "1 hour ago" ||
            	diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
            	day_diff == 1 && "Yesterday" ||
            	day_diff < 7 && day_diff + " days ago" ||
            	day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
		day_diff < 365 && Math.ceil( day_diff / 31 ) + " months ago " ||
		day_diff == day_diff && Math.ceil( day_diff / 365 ) + " years ago ";
}
 
/*
 * prettydate für die homepage mit jquery
 * haiko.hall@gmail.com
 */
 
function date2pretty(d){
    obj = new Date(d);
    return (obj.getTime()) ? prettyDate(obj) : d;
}
 
$(document).ready(function(){
    $("#target").click(function(){
        if($(this).attr("checked")){
            $("a").click(function(){this.target="_blank";});    
        }else{
            $("a").click(function(){this.target="";});
        }
    });
    $(".date").each(function(){
        $(this).html("<strong>"+date2pretty(this.innerHTML) + "</strong> | " + this.innerHTML)
    });
 
})
@import url(http://fonts.googleapis.com/css?family=Molengo|Droid+Sans+Mono);
 
 
 
body{
 
        font-family: "Molengo",serif;
 
        letter-spacing:.1em;
 
 
 
}
 
.item{
 
        margin-bottom:10px;
 
        text-align: justify;
 
}
 
 
 
.title{
 
        font-size: x-large;
 
        margin-bottom: 5px;
 
 
 
 
 
}
 
 
 
.date{
 
       color: #8E8E8E;
 
}
 
 
 
 
 
a{
 
        color:black;
 
        font-weight:bold;
 
}
 
 
 
h1,h2{
 
        border-bottom: 2px solid #A19AA5;
 
        color: black;
 
        font-weight: bolder;
 
}

~~DISCUSSION~~

Diese Website verwendet Cookies. Durch die Nutzung der Website stimmen Sie dem Speichern von Cookies auf Ihrem Computer zu. Außerdem bestätigen Sie, dass Sie unsere Datenschutzbestimmungen gelesen und verstanden haben. Wenn Sie nicht einverstanden sind, verlassen Sie die Website.Weitere Information
webdev/stuff/xml-rss-feeds-mit-php-und-yql-beziehen.txt · Zuletzt geändert: 2012/07/10 07:37 (Externe Bearbeitung)

hello, world