How to load Twitter user’s list in PHP


I made a simple method to load (and cache) tweets from all users of a particular Twitter list. Lists can be defined in any user’s account, and other Twitter users can then be added to them. Lists are public and are a good way to segment users by topic. Other users can then view to the list to see tweets from only users on the list. Only owners of the list can add or delete users, but anyone can see who is on a list (or what lists they are listed on).

To parse this information server-side in PHP, you can use the following method:

$tmpRoot = '/tmp';

/*
* Method to get timeline of specified user content
*/
function twitterGetList($username='', $listname='', $qty=0) {
	global $tmpRoot;

	$cacheFile	= $tmpRoot.'twitterCache-'.$username;

	if(file_exists($cacheFile)) {
		$cached	= unserialize(file_get_contents($cacheFile));

		if(time() <= $cached['expires']) {
			return $cached['data'];
		}
	}

	if($username != '' && $listname != '' && $qty > 0) {
		$url	= 'https://api.twitter.com/1/'.$username.'/lists/'.$listname.'/statuses.json';

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$curlout = curl_exec($ch);
		curl_close($ch);
		$tweets = json_decode($curlout, true);

		$return	= array();

		if(is_array($tweets)) {
	 		foreach($tweets as $tweet) {
				if(count($return) == $qty)
					break;

				$r		= array();
				$text	= $tweet['text'];
				$text	= explode(' ',$text);
				$count	= count($text);

				for($ii=0;$ii 1) {
						$user		= substr($text[$ii],1);
						$text[$ii]	= ''.$text[$ii].'';
					}

					if((substr($text[$ii],0,7) == 'http://' || substr($text[$ii],0,7) == 'https://') && strlen($text[$ii]) > 1) {
						$link		= substr($text[$ii],0);
						$text[$ii]	= ''.$text[$ii].'';
					}
				}

				$text					= implode(' ',$text);

				$r['text']				= $text;
				$r['username']			= $tweet['user']['screen_name'];
				$r['profile_image']		= $tweet['user']['profile_image_url'];

				array_push($return,$r);
			}
		}

		// cache results
		$cache				= array();
		$cache['expires']	= time() + 3600; // +1 hours
		$cache['data']		= $return;

		$fp = @fopen($cacheFile, 'w');

		if($fp !== FALSE) {
			fwrite($fp, serialize($cache));
			fclose($fp);
		}

		return $return;
	}

	return NULL;
}

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word