PHP: getting latest Tweets and displaying them in HTML

This post shows how you can get the latest Tweets from a Twitter account and displaying them in HTML, with links for all the entities (urls, hashtags, user mentions, etc).

Create a Twitter App

You must create a Twitter application and get a couple of tokens that will be used later. You should be able to create an application from here: https://apps.twitter.com/.

For more detailed steps take a look here: http://stackoverflow.com/questions/12916539/simplest-php-example-for-retrieving-user-timeline-with-twitter-api-version-1-1/15314662#15314662.

Get latest Tweets

For retrieving the latest tweets from the Twitter APIs we’ll use the J7mbo’s TwitterAPIExchange library (great and very simple). Other libraries are listed here: https://dev.twitter.com/overview/api/twitter-libraries.

The API we need to use is the statuses/user_timeline and we’ll get the JSON returned by this API converted as PHP object. You can use the library you prefer, provided that you can get the PHP object from the JSON returned from the Twitter’s API.

Example

This is a simple code that use the TwitterAPIExchange library and gets the latest tweets from our Twitter account named netglooweb:

// Require J7mbo's TwitterAPIExchange library (used to retrive the tweets)
// You can get this library from here: https://github.com/J7mbo/twitter-api-php
require_once('vendor/j7mbo/twitter-api-php/TwitterAPIExchange.php');

// Set here your twitter application tokens
$settings = array(
  'consumer_key' => 'CONSUMER_KEY',
  'consumer_secret' => 'CONSUMER_SECRET'
  
  // These two can be left empty since we'll only read from the Twitter's 
  // timeline
  'oauth_access_token' => '',
  'oauth_access_token_secret' => '',
);

// Set here the Twitter account from where getting latest tweets
$screen_name = 'netglooweb';

// Get timeline using TwitterAPIExchange
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = "?screen_name={$screen_name}";
$requestMethod = 'GET';

$twitter = new TwitterAPIExchange($settings);
$user_timeline = $twitter
  ->setGetfield($getfield)
  ->buildOauth($url, $requestMethod)
  ->performRequest();

$user_timeline = json_decode($user_timeline);

Inside the $user_timeline we’ll have the API response as PHP object, containing the latest tweets.

Format tweets in HTML with TwitterTextFormatter

The main problem with each library that wraps the Twitter’s APIs is that the returned tweets are pure text and they don’t provide the HTML formatted text.

In order to get the tweet’s text formatted in HTML, with links for all the tweet’s entities, we use the PHP class Netgloo\TwitterTextFormatter. You can download it from here.

In contrast to commons methods, such class uses the Twitter’s entities retrieved from the api response, instead of replacing URLs and entities using regular expression that is an error prone method.

Usage example

Referring the code listed before, we can use the TwitterTextFormatter class in this way:

// Require our TwitterTextFormatter library
// You can get this class from here: https://goo.gl/bTfdWS
require_once('TwitterTextFormatter.php');

// Use the class TwitterTextFormatter
use Netgloo\TwitterTextFormatter;

// Use the code above to fill the $user_timeline with latest tweets

// ...

// Print each tweet using TwitterTextFormatter to get the HTML text
echo "<ul>";
foreach ($user_timeline as $user_tweet) {
  echo "<li>";
  echo TwitterTextFormatter::format_text($user_tweet);
  echo "</li>";
}
echo "</ul>";

Try it yourself

You can get the code used in this post from our Github repository and try it by yourself:

https://github.com/netgloo/php-samples/tree/master/php-twitter-text-formatter

Appendix A: some useful fields from Twitter API

The following are some useful fields you can get from the tweet object returned by the API (e.g. the $user_tweet object in the code above). For most of them the name is self-descriptive:

  • created_at
  • retweet_count
  • entities->media: an array of all the media related to this tweet (I think for now it’s used only for the tweet’s attached photo).
  • user->name
  • user->screen_name
  • user->profile_image_url
  • retweeted_status: if this properties is set (check it with the PHP function isset) the current tweet is a “re-tweet” (and the fields below are available).
  • retweeted_status->user->name
  • retweeted_status->user->screen_name
  • retweeted_status->retweet_count

Example

This code will print also the tweet’s image:

  // ...

  if (isset($user_tweet->entities->media)) {
    $media_url = $user_tweet->entities->media[0]->media_url;
    echo "<img src='{$media_url}' width='100%' />";
  }
  
  // ...

Appendix B: installing PHP curl

PHP curl is a requirement for using PHP wrappers for the Twitter APIs.

On Ubuntu 14.04 you can install it with:

$ sudo apt-get install php5-curl
$ sudo service apache2 restart

References

http://blog.jacobemerick.com/web-development/parsing-twitter-feeds-with-php/
https://github.com/J7mbo/twitter-api-php
https://dev.twitter.com/oauth/application-only
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
https://dev.twitter.com/rest/public/timelines
http://php.net/manual/en/function.substr-replace.php#59544
http://iag.me/socialmedia/build-your-first-twitter-app-using-php-in-8-easy-steps/

Another good Twitter API wrapper
https://twitteroauth.com/

  • Nathan Bernard

    Hi Andrea. Thisplugin is great and easy to use 🙂 Thanks for that. I’d have a question though using “get tweets in php”. Is there any way to retrieve the tweet depending on a hashtag? Something we could set in the $config? thanks 🙂

    • Hi Nathan. No, for now there is not such option, I’m sorry. I will keep it in consideration for the next release. Thank you.

      • dpc

        any development with the hastags?

  • Joe Pritchard

    Hey Andrea, hope you don’t mind me leaving this here, I’ve taken your text formatter code and rolled it into a laravel package (although the class could be used anywhere) – Thought it may be helpful and easier to install into existing projects, since it can be pulled down as a composer package and refrerenced directly. The repo is here: https://github.com/joe-pritchard/laravel-twitter-text-formatter

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo