yourdev.ch » Code & Script Details
FacebookTwitterDel.icio.usMr. Wong
Yourdev auf Twitter unter yourdev_ch

PHP Twitter-Klasse

Kleine PHP Klasse um Tweets mit dem Twitter Benutzername abzurufen ohne das Passwort einzugeben.

Eine kleine und feine PHP Klasse um Tweets von einem Server abzurufen ohne eine Verbindung zur API (also ohne Passwort) herzustellen. Dies kann sicherlich in einer längeren Ladezeit resultieren. Die Tweets werden aber nach dem Aufruf in einem cache file gespeichert und von dort aufgerufen (Ein Cronjob könnte die Zeit um neu zu cachen für den Client übernehmen!)

 Hier nun ein kleines Beispiel um die Klasse aufzurufen und Tweets wieder zu geben.

include('twitter.class.php');

$client = new Twitter('yourdev_ch');
$client->cache_file = 'cache/twittercache.txt'; // set chmod 0777 to this file
$tweets_array = $client->getTweets();

if($tweets_array === false) {
   exit('error while loading tweets:' . $client->error);
}

foreach($tweets_array as $item) {
   echo "text: {$item['text']} am datum: " . date("d.m.Y H:i", $item['date']);

Hier noch die dazu gehörige twitter.class.php welche natürlich vorher noch included werden muss. Download als ZIP

class Twitter {
public $cache_time = 1800; // 30 minutes of caching time
public $cache_file = 'cache/twitter_cache.txt'; // chmod 0777

public $start_tweet = 1; // will start at tweet number $start_tweet;

public $end_tweet = 25; // will stop at tweet number $end_tweet upon from $start_tweet

private $tweet_array = array(); // contains the tweets

private $account = null; // containts the twitter user name

private $request = 'http://www.twitter.com/statuses/user_timeline/'; // url shema {$username}.json

public $error = null; // error message

public function __construct($twitter_account)
{
$this->account = $twitter_account;
}

/*
* public method to get the tweets for this account.

* @return will return false if sth went wrong; will return an array if everything went right
*/
public function getTweets()
{
if(!$this->loadAndCache()) return false;

foreach($this->tweet_array as $k => $v)
{

$return[] = array(
'date' => strtotime($v->created_at),
'id' => $v->id,
'text' => $this->textHighlights($v->text),
'retweets' => $v->retweet_count,
'account' => $this->account,
'link' => "http://twitter.com/{$this->account}/status/{$v->id}"
);

if(($k+1) >= $this->end_tweet) break;
}

return $return;

}

/**
* load the files from cache or recache the file and load from server

* @return boolean
*/
private function loadAndCache()
{
if(file_exists($this->cache_file) && time() - $this->cache_time < filemtime($this->cache_file))
{
$this->tweet_array = unserialize(file_get_contents($this->cache_file));
} else {
$this->tweet_array = $this->requestFromServer();
$handle = @fopen($this->cache_file, 'w');
if(!$handle)
{
$this->error = "can not write file cache; check the permissions of '{$this->cache_file}'"; return false;
}
fwrite($handle, serialize($this->tweet_array));
fclose($handle);
}

return true;
}

/**
* Request the tweets from twitter serveri via curl or file_get_contents.
* Curl must be intalled on the webserver or allow_url_fopen is 1 in your php.ini (try echo phpinfo(); to find out)

* @return boolean
*/
private function requestFromServer()
{
if(function_exists('curl_init'))
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->request . $this->account . '.json');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
} elseif((bool)ini_get('allow_url_fopen'))
{
$json = file_get_contents($this->request . $this->account . '.json', "r");
}

if(!isset($json)) return false;

return json_decode($json);
}

/**
* make links to hash tags; add href for links

* @param $text [string] full tweet text
*/
private function textHighlights($text)
{
$text = preg_replace('@(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $text);

// find hash tag's and generate links to twitter search
$preg = preg_match_all("/#([a-zA-Z0-9]+)/", $text, $result, PREG_SET_ORDER);

foreach($result as $item)
{
$text = str_replace($item[0], '<a target="_blank" href="http://twitter.com/#search/%23'.$item[1].'">'.$item[0].'</a>', $text);
}

return $text;
}
}

Letzte Beitrag änderung am 16.02.2011 um 10:05 Uhr

Fragen zum Script, einen Fehler melden oder eine wichtige ergänzung mitteilen? Kontaktieren Sie uns einfach.

Kommentar verfassen

Nambé - Design your Life

Nambé - Design your Life Hochwertige, handgemachte Produkte für den Tisch und die Küche » Zum Portfolio

PHP Lab auf YourDev

PHP Lab auf YourDev PHP Lab - Gratis und Hilfreich für Jedermann! » Alle Anzeigen

Links