Pixel Acres

TweetPHP: Display tweets on your website using PHP

If you’ve ever wanted to display your latest Twitter tweets on a website, TweetPHP lets you do that using PHP. TweetPHP is a rewrite of my old Twitter RSS feed parser, which stopped working when Twitter phased out their v1 API.

Features

  • Works with Twitter API v1.1
  • Tweets are cached to avoid exceeding Twitter’s API request rate limits
  • A fallback is provided in case the twitter feed fails to load
  • Retweets and @replies can be optionally ignored
  • A configuration parameter allows you to specify how many tweets are displayed
  • Dates can optionally be displayed in “Twitter style”, e.g. “12 minutes ago”
  • You can customize the HTML that wraps your tweets, tweet status and meta information

Download

TweetPHP is available on Github

Usage

To interact with Twitter’s API you will need to create an API KEY, which you can create at: https://dev.twitter.com/apps

After creating your API Key you will need to take note of following values: “Consumer key”, “Consumer secret”, “Access token”, “Access token secret”

Those values can be passed as options to the class constructor, along with the Twitter screen name you wish to query:

require_once('TweetPHP.php');

$TweetPHP = new TweetPHP(array(
  'consumer_key'              => 'xxxxxxxxxxxxxxxxxxxxx',
  'consumer_secret'           => 'xxxxxxxxxxxxxxxxxxxxx',
  'access_token'              => 'xxxxxxxxxxxxxxxxxxxxx',
  'access_token_secret'       => 'xxxxxxxxxxxxxxxxxxxxx',
  'twitter_screen_name'       => 'yourusername'
));

Then you can display the results like so:

echo $TweetPHP->get_tweet_list();

Options

Options can be overridden by passing an array of key/value pairs to the class constructor. At a minimum you must set the consumer_key, consumer_secret, access_token, access_token_secret and twitter_screen_name options, as shown above.

Here is a full list of options, and their default values:

'consumer_key'          => '',
'consumer_secret'       => '',
'access_token'          => '',
'access_token_secret'   => '',
'twitter_screen_name'   => '',
'cache_file'            => dirname(__FILE__) . '/cache/twitter.txt', // Where on the server to save the cached formatted tweets
'cache_file_raw'        => dirname(__FILE__) . '/cache/twitter-array.txt', // Where on the server to save the cached raw tweets
'cachetime'             => 60 * 60, // Seconds to cache feed (1 hour).
'tweets_to_display'     => 10, // How many tweets to fetch
'ignore_replies'        => true, // Ignore @replies
'ignore_retweets'       => true, // Ignore retweets
'twitter_style_dates'   => false, // Use twitter style dates e.g. 2 hours ago
'twitter_date_text'     => array('seconds', 'minutes', 'about', 'hour', 'ago'),
'date_format'           => '%I:%M %p %b %d%O', // The defult date format e.g. 12:08 PM Jun 12th. See: http://php.net/manual/en/function.strftime.php
'date_lang'             => null, // Language for date e.g. 'fr_FR'. See: http://php.net/manual/en/function.setlocale.php
'format'                => 'html', // Can be 'html' or 'array'
'twitter_wrap_open'     => '<h2>Latest tweets</h2><ul id="twitter">',
'twitter_wrap_close'    => '</ul>',
'tweet_wrap_open'       => '<li><span class="status">',
'meta_wrap_open'        => '</span><span class="meta"> ',
'meta_wrap_close'       => '</span>',
'tweet_wrap_close'      => '</li>',
'error_message'         => 'Oops, our twitter feed is unavailable right now.',
'error_link_text'       => 'Follow us on Twitter',
'debug'                 => false

Caching

Caching is employed because Twitter rate limits how many times their feeds can be accessed per hour.

When the user timeline is first loaded, the resultant HTML list is saved as a text file on your web server. The default location for this file is: cache/twitter.txt

You can change this file path by setting the cache_file option. For example, to set a path from your root public directory try:

$_SERVER['DOCUMENT_ROOT'] . '/path/to/my/cache/dir/filename.txt'

Debugging

If you are experiencing problems using the plugin please set the debug option to true. This will set PHP’s error reporting level to E_ALL, and will also display a debugging report.

Here are a few tips to help you solve common configuration issues:

tmhOAuth response code: 0

If your debugging report shows the error “tmhOAuth response code: 0″, you can find out more about this error message in the tmhOAuth github README. Dario also offers this solution: “My server didn’t like the the two __DIR__ constants in the tmhOAuth.php file, hard-coded them and it all works now.”

unserialize error

If you receive the PHP warning “[function.unserialize]: Error at offset 0 of 49 bytes”, it might be the case that you have magic quotes enabled in your PHP configuration.

Credits

- Feed parsing uses Matt Harris’ tmhOAuth
- Hashtag/username parsing uses Mike Cochrane’s twitter-text-php

66 Responses to “TweetPHP: Display tweets on your website using PHP”

  1. Bart says:

    Good morning! I’ve been trying to use this plugin, but can’t seem to get it working. The cache .txt files can’t be found, because the path to these files is wrong.

    The path is created as this:
    Warning: fopen(/home/bart747/domains/bveenhof.nl/public_html/portfolio./cache/twitter.txt) [function.fopen]: failed to open stream: No such file or directory in /home/bart747/domains/bveenhof.nl/public_html/portfolio/TweetPHP.php on line 153

    The problem is this: portfolio. There’s a dot after portfolio, which is why the path is incorrect. I can’t seem to find out where this dot is coming from though… Any thoughts on where it could come from?

    Thanks in advance!

  2. Bart says:

    magically started working! :) Well, sort of. Getting this error right now:

    Cache expiration timestamp: 1391588499
    Cache file timestamp: 1391522282
    Cache file doesn’t exist or is older than cachetime.
    Fetching fresh tweets using Twitter API.
    tmhOAuth response code: 200
    No tweets were found. error_message will be displayed.

    I’ll try to mess around more :)

  3. Bart says:

    Sorry for spamming this page, but the previous problem has sorta solved itself too. Although i still have this error:

    Cache expiration timestamp: 1391588499
    Cache file timestamp: 1391522282
    Cache file doesn’t exist or is older than cachetime.

    The tweets are not loaded. However, when i delete the cache .txt files the Tweets work fine. There´s a huge error though because it can´t locate the .txt files anymore :(

  4. Marty says:

    Hello. I am trying to get this to work on my website, but when ever I call the TweetPHP function, everything seems to stop working and just not load.
    I am requiring the php file and after that calling the function (passing the options into it) like it says. But cant seem to make it work.
    I have turned on error reporting, but am also not getting any errors displayed.

  5. Al says:

    I have tried for a few hours to get this working. I created a test script http://www.gallerychurchbaltimore.com/twitter/twitter.php
    turning on the debug I only see my twitter.txt cache file.
    I cannot seem to pull the latest tweets down using the script. I have actually tried putting all the options into my test script also with same results.

    my debug output is
    Cache expiration timestamp: 1392319597
    Cache file timestamp: 1392322781
    Cache file is newer than cachetime.
    HI Al This is the default twitter.txt cache file.

  6. Jonathan says:

    @Marty If your page just dies then that’s probably due to a PHP error. Turn on PHP error reporting so you can see the error message. You may need to view the source of the rendered page to see the message.

  7. Jonathan says:

    @Al To figure out why your tweets are not being pulled from Twitter, you should delete the two cache .txt files. The next time the script runs it will try to fetch your timeline from Twitter, and the debug messages might give a clue why that transaction is failing.

    The two most likely reasons are:

    1) You haven’t correctly created your Twitter API key, or populated TweetPHP with those values (see the usage section of this article). I would expect to see a thmOAuth error message in that case.

    2) TweetPHP is able to fetch your timeline from Twitter (it will display them on your site), but is unable to write the tweets to the cache. You’ll know if that’s happening because the cache files will not be recreated after you delete them.

  8. gundam says:

    thx you ^^v
    I’m succeded using this..but share my story first
    * i tried make app (failed). I must enter my phone
    * I type my phone in setting and got charge bout $1 (nah.. not big deal)..
    * I supposed is should respond to twitter accepted my phone but isn’t?!? anyway skip this and i return to the app.. and succed make the app!!
    * in https://apps.twitter.com/app/xxxx (xx:number), click API Keys
    * generated API Keys (dont forget about permision)
    * API key&API secret goes to consumer_key&consumer_secret
    * access token&secret is same
    * delete cache..

    the problem? I don’t see any. hope everything is fine

  9. Martyn says:

    Can you give me some guidance around the “twitter_date_text” option? I’d quite like it to say for example “3 days ago”. It seems it only does the “X ago” type text if it’s within the one day. Is that right? Can it be changed?

    Not a problem if not, I was just wondering.

  10. Jonathan says:

    @Martyn Yes, the “twitter style dates” will start showing an actual date when a tweet is a day old, which mimics the behaviour on Twitter. If you want to change that you could edit the date parsing logic which starts at line 184. There are currently switch cases for seconds, minutes and hours, and you’d need to change the default case to calculate the number of elapsed days and display that instead of the date.

  11. gundam says:

    I found something related to time. Since the detail are to long.. I posted on my blog. you can check on my blog link http://adapani.blogspot.com/2014/03/tweetphp-why-time-is-invalid.html

  12. José Luis says:

    Hi Jonathan. I’m using your script, and I’m wondering if it’s possible to automatically ‘refresh’ the tweets or, perhaps, include a button to do the task. Can you point me in the right direction? Thank you!!!

  13. Jonathan says:

    @José If you set the cachetime configuration option to a lower value, like 60 seconds, then the cache will purge and refresh every minute. This requires a page refresh obviously.

  14. gundam says:

    @jose try use cron.. is better than page refresh..
    but remember to ‘log’ every refresh you made on cron..

  15. Mark says:

    Hey man, for me it isn’t working.

    I get this error :

    PHP Notice: unserialize(): Error at offset 0 of 49 bytes in twitter/TweetPHP.php on line 90

  16. Jonathan says:

    @Mark That error message is explained in the post.

Leave a Reply