Scriptplayground Network

Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Twitter Integration Class Using PHP5 and cURL

Twitter Integration Class Using PHP5 and cURL

Learn how to create a Twitter integration Class using PHP5 and cURL.

This tutorial was graciously donated by Ryan Barr

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

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

$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.

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.

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.

echo '<ul>';
foreach($tweets as $tweet) 
{
  echo '<li>'. $tweet->content .' by <a href="http://twitter.com/'. $tweet->user .'">';
  echo '. $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.

About the Author

Ryan Barr is a professional web designer and developer. You can read this original post on his blog.

| Print It |  Follow Scriptplayground on Twitter (@scriptplay)

Comments: Twitter Integration Class Using PHP5 and cURL

 @libraties  Fri Jul 16, 2010 8:36 am  
Thanks for your great script! It works well, except for a few troubles I'm having.

There's this weird thing: If you use the 'OR' in the usernames, it will not only publish the messages from this user, but also the replies made to the user. (only the second user???) Is there a way to fix this?

Then I have a problem with the date. If I change this line:
$tweet->updated = (int) strtotime($entry->updated);
to this:
$tweet->updated = (int) date("j" . "n" . "Y", strtotime($entry->updated)) ;
I get the date, but without any spaces, dashes or what so ever. If I try to put this in the above, it will not show. I'm probably doing something wrong. (I only have basic PHP scales so writing is very difficult) Any solutions?

Last thing: I would really like to display only the tweets with a certain hashtag. Can't get it to work bij putting &tag="fillintag" in the url, and it would be way nicer if you could put this in the code block where you create the instance. Is it possible to add this to the code?

Hope you can help me, thanks in advance! @libraties
 @libraties  Fri Jul 16, 2010 9:02 am  
fixed the last thing in my comment, by adding this:

public function __construct($user, $limit = 5, $hashtag)
{
$user = str_replace(' OR ', '%20OR%20', $user);
$feed = curl_init('http://search.twitter.com/search.atom?q=from:'. $user .'&rpp='. $limit .'&tag='. $hashtag);

and this:
and $feed = new Twitter('username', 3, 'hashtagname');
 vivek  Mon Aug 16, 2010 1:00 am  
hi I am getting this error..please help me..
Fatal error: Call to undefined function curl_init() in D:lakshmiwwwtwittertweet.php on line 8
 OldJames  Fri Aug 20, 2010 11:00 am  
@vivek you must install the cURL library.
Your webserver must support PHP with cURL
ie. compile php --with-curl

http://www.php.net/manual/en/book.curl.php

 OldJames  Fri Aug 20, 2010 11:46 am  
@libraties

If your still having the problem with your date formatiing:
It's because your forcing the result to an integer, instead of a string.
$tweet->updated = (int) date("j" . "n" . "Y", strtotime($entry->updated)) ;

the (int) is forcing the return type to interger. Change this to (string) and your good.
 Jeff  Wed Sep 1, 2010 1:43 am  
First off, thanks for the PHP class.. definitely something that will come in handy in the future!

I recently demo'd out the code with a few different Twitter accounts and noticed that some accounts successfully pull the limit number of tweets that I have set while some accounts only pull the single latest tweet. I've even dealt with a twitter account that is only pulling the 2 latest tweets even though the limit is set at 5?

I haven't seemed to find a pattern between which accounts and what the difference is between each account to allow pulling the number of tweets successfully..

Has anyone dealt with this and any advice?
Add a comment
Name:
Website:
Comment:
Please note: Offensive comments, flaming and spamming is not permitted on this site and your comment will be deleted immediately.

HTML is not allowed.

Please provide all comments in English so that others can help you. A common helper in this is to use an online translator.

As a security measure your ip will be recorded.
 
Anti-Robot Check:

Enter the key you see above.

What is this?: This extra test has been added due to the recent explosion of spam.
 
Google