Twitter Integration Class Using PHP5 and cURL

May 18, 2010

For those familiar with the now defunct ‘Latest Twitter Update(s) with PHP’ series or for those who are looking for a fast, effective, and efficient way to integrate Twitter updates with their site without using JavaScript, OAuth or even a single password then this is the script for you. This is a PHP5 class which utilizes cURL to avoid any remote file-access problems with PHP. (In PHP5, remote file connections with fopen(), file_get_contents(), etc. are turned off to increase security and prevent things like XSS injections.)

Features

  • Pull up to 100 tweets from Twitter using the Search API.
  • Pull from multiple Twitter users at once. (Read below, some restrictions apply.)
  • Full customization as you are provided with an object (similar to an array) to echo data with.
  • Increased speed; can pull maximum tweets (100) in under half of a second.

Requirements

  • The latest stable version of PHP 5.x.x or higher is required. (This script will not work with PHP4.)

Important Notes

  • In order to pull from multiple Twitter users, you must simply place ‘ OR ‘ between each of the users in your request. For example, ‘ryanbarr OR mkeefe OR twitter’ will pull tweets from @ryanbarr, @mkeefe, and @twitter.
  • Twitter limits the Search API query to 140 characters total. After setting variables and how many tweets to be pulled, you are left with 127 characters. This is solely for your usernames. For example, ‘ryanbarr’ would be 8 characters. ‘ryanbarr OR mkeefe’ would be 22* characters.
    • *Note: The ‘ OR ‘ which is included is converted to ‘%20OR%20′ for Twitter API / URL purposes. So ‘ OR ‘ is actually 8 characters instead of only 4.
  • Some Twitter accounts will not show up in he Search API feed or will be heavily delayed. For more information refer to this Twitter article.

The PHP Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Twitter {
public $tweets = array();
public function __construct($user, $limit = 5) {
$user = str_replace(' OR ', '%20OR%20', $user);
$feed = curl_init('http://search.twitter.com/search.atom?q=from:'. $user .'&rpp='. $limit);
curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
curl_setopt($feed, CURLOPT_HEADER, 0);
$xml = curl_exec($feed);
curl_close($feed);
$result = new SimpleXMLElement($xml);
foreach($result->entry as $entry) {
$tweet = new stdClass();
$tweet->id = (string) $entry->id;
$user = explode(' ', $entry->author->name);
$tweet->user = (string) $user[0];
$tweet->author = (string) substr($entry->author->name, strlen($user[0])+2, -1);
$tweet->title = (string) $entry->title;
$tweet->content = (string) $entry->content;
$tweet->updated = (int) strtotime($entry->updated);
$tweet->permalink = (string) $entry->link[0]->attributes()->href;
$tweet->avatar = (string) $entry->link[1]->attributes()->href;
array_push($this->tweets, $tweet);
}
unset($feed, $xml, $result, $tweet);
}
public function getTweets() { return $this->tweets; }
}

Creating an Instance and Storing Tweets

1
2
$feed = new Twitter('ryanbarr', 5);
$tweets = $feed->getTweets();

Installation

  • Save a copy of the PHP class to your server. Feel free to combine it with other classes, or put it directly on the page(s) where needed (above the DOCTYPE is recommended).
  • Copy and paste the “creating an instance and storing tweets” code below where your class has been defined, and then include your username(s) and the desired amount of tweets.
    • Remember: You can pull from multiple users by separating them with ‘ OR ‘. Example: ‘ryanbarr OR mkeefe’.
  • If properly installed, $tweets should be a multi-dimensional array containing the number of tweets you requested from the user(s) you requested.

Implementation

Implementing the freshly pulled tweets into your page is extremely easy and only requires a slight bit of PHP knowledge on handling and outputting data from an array. Remember: in array keys, [0] would be the first entry whereas [4] would be the fifth entry.

Example 1: Calling Data Directly

In this example, we will be considering that a total of 5 tweets were to be pulled from my Twitter account. Calling data directly from the array will allow you to place each individual tweet differently on the page.

1
2
echo $tweets[0]->content; // Displays the content from the latest tweet.
echo $tweets[4]->content; // Displays the content from the oldest tweet.

Example 2: Looping Data

In this example, we will be considering that a total of 5 tweets were to be pulled from my Twitter account. Looping the data allows you to perform the same actions on each tweet with far less code.

1
2
3
foreach ($tweets as $tweet) {
echo $tweet->content;
}

Example 3: Looping Data Into an Unordered List

In this example, we will be considering that a total of 5 tweets were to be pulled from my Twitter account. As mentioned above, looping data allows you to apply the same actions to each tweet you receive. This example is a more elaborate version of the above which puts the tweets into a list with the tweet, the author, and a link to the author’s Twitter profile.

1
2
3
4
5
echo '<ul>';
foreach ($tweets as $tweet) {
echo '<li>'. $tweet->content .' by <a href="http://twitter.com/'. $tweet->user .'">'. $tweet->author .'</a></li>';
}
echo '</ul>';

Tweet Content Reference Guide

  • $tweets[0]->id OR $tweet->idThe unique reference ID for the tweet.
  • $tweets[0]->user OR $tweet->userThe Twitter username for the author of the tweet.
  • $tweets[0]->author OR $tweet->authorThe display name for the author of the tweet.
  • $tweets[0]->title OR $tweet->titleThe content of the tweet without formatting; plain text tweet.
  • $tweets[0]->content OR $tweet->contentThe content of the tweet with formatting; includes links, special characters, etc.
  • $tweets[0]->updated OR $tweet->updatedThe UNIX timestamp for when the tweet was posted. (Use date() to display a date string.)
  • $tweets[0]->permalink OR $tweet->permalinkThe URL for the individual tweet on Twitter.
  • $tweets[0]->avatar OR $tweet->avatarThe URL for the author’s avatar. (Use <img> to include it in your page.)

Advanced Modifications and Queries

If you’re an experienced PHP developer, or have the guts to dive into unknown waters, there are a few things you can do further using the Twitter Search API reference guide and some modifications to the URL string passed to cURL. Some of these things include:

  • Pulling tweets in a single language.
  • Pagination queries to limit the results passed from Twitter.
  • Timestamp-dependent queries to limit when a tweet had to be made by to be passed.
  • Geo-location queries to limit an area from where a tweet was made.
  • Type queries to switch between popular/trending tweets and realtime tweets.
  • Many other modifications across all possible Search timelines.

Further Help, Support, and Requests

All questions, comments, concerns and feature-requests should be directed to the comments. If you have a critical issue or are in need of paid assistance, please feel free to e-mail me at ryanbarr [at] gmail .dot. com. (Requests in languages other than English are welcomed, however I cannot guarantee a proper or clear response.)

Disclaimer and Credits

When using this code you understand the risks of an script which may include, but are not limited to: hacking attempts, memory leaks, server malfunctions, etc. The author(s) of this script are not liable for any damages that may result from the use of this script by any form of user.

This code was the result of many hours of concentration, minimizing, and optimizing. Matthew Keefe generously donated some of his time to help test and optimize the code during a late night, please give him your thanks as well.

Enjoy the code and check back for updates!

Tags: , , ,

If you've enjoyed this post you may enjoy reading my tweets on Twitter and you can follow me at @ryanbarr. Interested in working together? Shoot me an e-mail at ryanbarr [at] gmail .dot. com and we can discuss your next project or opportunity!

12 Responses

  1. Sorry, this might be an incredibly dumb question, but where or which is the “creating an instance and storing tweets” code?

  2. @Mia: not a dumb question at all, it seems WordPress lost the snippet in a draft while I was writing the tutorial. It has been added now and can be found underneath the class code. Thanks for catching that!

  3. No problem! Thanks for this article!

  4. One more question: is there a way for this code to just only pull items from the accounts and not post random people’s replies to those accounts?

  5. Hey Mia,

    Can you paste the snippet of code where you “created the instance”? The from: parameter in the url (hard coded within the class) limits only from a user. You aren’t putting the @ sign in front of usernames when you are calling them through the function, correct?

    For example, if I wanted to pull from my Twitter account, @ryanbarr, I would set ‘ryanbarr’ in the function.

    Best,
    Ryan

  6. No, I didn’t put the @ sign. Just this:

    $feed = new Twitter(‘username OR username OR username’, 5);
    $tweets = $feed->getTweets();

    Was I supposed to change something in the PHP Class?

  7. Sequoia McDowell

    June 2nd, 2010

    Thanks so much, and let me say, what a well written tutorial! Personally I’d be alright using the class and var_dumping the results and going from there, but it’s really great to see things explained in a detailed way that is friendly to the novice or non-programmer.

    Kudos to you!

  8. Great bit of code I’m trying to figure out how to work the avatar bit of it. Could you explain how that works? I don’t know much about PHP.

    Thanks.
    iHonda

  9. @Sequoia Thank you, I appreciate the kind words.

    @iHonda The absolute path (for example: http://example.com/image.jpg) is stored in the $tweet->avatar object. To display it on a page, simply call it within the source of an img element. For example:

    1
    <img src="<?php echo $tweet->avatar; ?>" alt="Avatar" />

    Hope that clears things up for you!

  10. @Mia, After a bit of research, I’m still uncertain what may be holding you back. Do you have a live example of it pulling mentions to the accounts you’re pulling tweets from?

  11. Stephan

    June 7th, 2010

    Nice script. Thank you!

    But there is one question: is it right that it pulled only the feeds of the actual month? Is there a posibility to get older feeds?

    Thank you,
    Stephan.

  12. @Stephan,

    There is certainly something wrong with your script if it is limiting itself to a certain timeframe. How many tweets are you trying to pull?

Leave a Reply