Please Log In to save to favorites
TAGs
php, rss, feed, twitter, regular expressions, regex


Versions
Show Feed (Twitter)
I still dislike the way PHP handles XML files, and sometimes end up using regular expressions to get the data I need. Here is an example of how I would get twitter feeds and display them.

It includes caching as an option and also relies on an external function called getHowLongAgo(). - more on that later.
      
    1.   // enter in feed url here
    2.   $url = "";
    3.   // enter in where you want to save the cache
    4.   $file = "file_location";
    5.   if ( !file_exists($file) ) {
    6.    fclose(fopen($file, "w+"));
    7.   }
    8.   $last_modified = filemtime($file);
    9.   $time = (time() - $last_modified)/60/24;
    10.   if ( $time > 1 ) {
    11.    $str = file_get_contents($url);
    12.    $handle = fopen($file, "w+");
    13.    fwrite($handle, $str);
    14.    fclose($handle);
    15.   }
    16.   $handle = fopen($file, "r");
    17.   $str = fread($handle, filesize($file));
    18.   fclose($handle);
    19.   preg_match_all("/<item>.+?<\/item>/is", $str, $array);
    20.   if ( !empty ( $array ) ) {
    21.    foreach ( $array[0] as $arr ) {
    22.    preg_match("/<title>(.+?)<\/title>/s", $arr, $title);
    23.    $title[1] = preg_replace("/.+?:/", "" , $title[1]);
    24.    preg_match("/<pubDate>(.+?)<\/pubDate>/s", $arr, $date);
        $date = getHowLongAgo(date("Y-m-d H:i:s", strtotime($date[1])));
    26.    // please note that this does not include the link to the tweet
    27.    echo '<div>'.$title[1]."<br>".$date."</div>";
    28.    }
    29.   }
Comments


getHowLongAgo()

Posted by: duniyadnd around 18 Months Ago
Line: 25

You can get the code from this link