A PHP class for querying the Twitter API and rendering tweets as an HTML list

Overview

TweetPHP

A PHP class for querying the Twitter API and rendering tweets as an HTML list.

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 API request fails
  • 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

Authentication

To interact with Twitter's API you will need to create a Twitter application at: https://dev.twitter.com/apps

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

Usage

Your API credentials can be passed as options to the class constructor, along with the any other configuration options:

$TweetPHP = new TweetPHP(array(
  'consumer_key'        => 'xxxxxxxxxxxxxxxxxxxxx',
  'consumer_secret'     => 'xxxxxxxxxxxxxxxxxxxxx',
  'access_token'        => 'xxxxxxxxxxxxxxxxxxxxx',
  'access_token_secret' => 'xxxxxxxxxxxxxxxxxxxxx',
  'api_params'          => array('screen_name' => 'twitteruser')
));

Then you can display the results like so:

echo $TweetPHP->get_tweet_list();

You can also retreive the raw data received from Twitter:

$tweet_array = $TweetPHP->get_tweet_array();

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 options, as shown above.

You should also set an api_endpoint and api_params, an array of parameters to include with the call to the Twitter API.

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

{tweets}', 'tweet_template' => '
  • {tweet}{date}
  • ', 'error_template' => '
  • Our twitter feed is unavailable right now. Follow us on Twitter
  • ', 'nofollow_links' => false, // Add rel="nofollow" attribute to links 'debug' => false ">
    'consumer_key'          => '',
    'consumer_secret'       => '',
    'access_token'          => '',
    'access_token_secret'   => '',
    'api_endpoint'          => 'statuses/user_timeline',
    'api_params'            => array(),
    'enable_cache'          => true,
    'cache_dir'             => dirname(__FILE__) . '/cache/', // Where on the server to save cached tweets
    'cachetime'             => 60 * 60, // Seconds to cache feed (1 hour).
    'tweets_to_retrieve'    => 25, // Specifies the number of tweets to try and fetch, up to a maximum of 200
    'tweets_to_display'     => 10, // Number of tweets to display
    '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 %e%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
    'twitter_template'      => '

    Latest tweets

      {tweets}
    ', 'tweet_template' => '
  • {tweet}{date}
  • ', 'error_template' => '
  • Our twitter feed is unavailable right now. Follow us on Twitter
  • ', 'nofollow_links' => false, // Add rel="nofollow" attribute to links 'debug' => false

    Deprecated options

    The following options have been deprecated. You should use api_params to set API parameters instead.

    'twitter_screen_name'   => ''
    'ignore_replies'        => true
    'ignore_retweets'       => true
    

    API endpoints

    Since TweetPHP uses Twitter's Application-only API authentication model, it can only access certain GET endpoints.

    It has been tested with the statuses/user_timeline endpoint (its default) and the search/tweets endpoint.

    Examples

    Fetch a user's timeline

     'xxxxxxxxxxxxxxxxxxxxx',
      'consumer_secret'     => 'xxxxxxxxxxxxxxxxxxxxx',
      'access_token'        => 'xxxxxxxxxxxxxxxxxxxxx',
      'access_token_secret' => 'xxxxxxxxxxxxxxxxxxxxx',
      'api_endpoint'        => 'statuses/user_timeline',
      'api_params'          => array('screen_name' => 'twitteruser')
    ));
    
    echo $TweetPHP->get_tweet_list(); 
    ?>
    

    Note that the api_endpoint option could be omitted in this case, since 'statuses/user_timeline' is its default value.

    Search for a hashtag

     'xxxxxxxxxxxxxxxxxxxxx',
      'consumer_secret'     => 'xxxxxxxxxxxxxxxxxxxxx',
      'access_token'        => 'xxxxxxxxxxxxxxxxxxxxx',
      'access_token_secret' => 'xxxxxxxxxxxxxxxxxxxxx',
      'api_endpoint'        => 'search/tweets',
      'api_params'          => array('q' => '#php', 'result_type'=>'latest')
    ));
    
    echo $TweetPHP->get_tweet_list(); 
    ?>
    

    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

    The raw Twitter response is saved as a serialized array in: cache/twitter-array.txt

    You can change these file paths using the cache_dir option. For example, to set a path from your root public directory try:

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

    Debugging

    If you are experiencing problems using the script 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.

    You can also fetch the debugging report as an array or HTML list, even when the debug option is set to false:

    echo $TweetPHP->get_debug_list();
    $debug_array = $TweetPHP->get_debug_array();
    

    Helper methods

    autolink

    Pass raw tweet text to autolink() and it will convert all usernames, hashtags and URLs to HTML links.

    $autolinked_tweet = $TweetPHP->autolink($tweet);
    

    This might be handy if you want to process tweets yourself, using the array returned by get_tweet_array().

    Credits

    Comments
    • Most options don't work.

      Most options don't work.

      I know the options are being read because the debug one is the only one that has had any affect so far.

      I've tried to limit the display of tweets to 1, and it's still showing two. Have also tried to remove the h2 header, but it still remains.

      All done in this format:

      'twitter_wrap_open'         => '<ul id="tweets">',
      'twitter_wrap_close'        => '</ul>'
      

      Any idea as to why the options are being ignored?

      opened by ghost 11
    • Parsing images from tweets added

      Parsing images from tweets added

      The lib works great, but I found that if the tweet contains an image we have no way of displaying it. In accordance with the code style, this fork adds image parsing from tweets and makes a new {img} handler, that can be used in templates, that spits out the URL of the image of the tweet, if there is any.

      enhancement 
      opened by Nualiian 8
    • Need to add rel=

      Need to add rel="nofollow" to all links

      I've trie dto use tweet_template to change links to have rel="nofollow" but what can I do to links that are actually inside the tweet itself? Can I apply the same rel="nofollow" to those?

      'tweet_template' => '<li><span class="status">{tweet}</span><span class="meta"><a rel="nofollow" href="{link}">{date}</a></span></li>'

      (However the line above doesn't seem to change the output, instead I get the normal link, but with no date where {date} should be, it's just an empty link element).

      You can see this at http://development.bellavou.co.uk (email me for username/password please)

      opened by ghost 6
    • a way to set hashtags via options or another way?

      a way to set hashtags via options or another way?

      Via the JS version you can use

      <a class="twitter-timeline" href="https://twitter.com/hashtag/GE2015" data-widget-id="611481458889355264">#GE2015 Tweets</a>

      to filter the feed.

      enhancement 
      opened by v3nt 5
    • No dates showing

      No dates showing

      The template is appearing, but no dates are showing up in the values, regardless of different options given.

      No obvious reason as to why. The dates are being returned in 'created_date' when using the array.

      Any ideas?

      opened by ghost 5
    • Notice: Undefined variable: responsedata in tweet-php/TweetPHP.php on line 155

      Notice: Undefined variable: responsedata in tweet-php/TweetPHP.php on line 155

      I think you have to change the variable $responsedata to $response on line 155.

      From $data = array_key_exists('statuses', $response) ? $response['statuses'] : $responsedata;

      to $data = array_key_exists('statuses', $response) ? $response['statuses'] : $response;

      opened by spadilha 1
    • tweets_to_retrieve and tweets_to_display don't match results?

      tweets_to_retrieve and tweets_to_display don't match results?

      fullsizeoutput_1e35 Ie I have these set as below but only 5 showing? Maybe replies and retweets are being included even though set to be excluded?

                'tweets_to_retrieve'    => 24, 
                'tweets_to_display'     => 12, // Number of tweets to display
                'ignore_replies'        => true, // Ignore @replies
                'ignore_retweets'       => true, // Ignore retweets
      

      [screenshot attached]

      opened by v3nt 1
    • how do you actually add this to a php file and run it?

      how do you actually add this to a php file and run it?

      Can't seem to get this working and just want to grab a basic feed. Seems like all the paths aren't quite right?

      If i wanted to run echo $TweetPHP->get_tweet_list(); how would i reference the TweetPHP class?

      opened by v3nt 1
    • Change Twitter style dates to respect the user's timezone instead of the server's.

      Change Twitter style dates to respect the user's timezone instead of the server's.

      The twitter style dates function was using time() to compare the tweet date against instead of accounting for the twitter user's timezone, which the regular dates style already does.

      opened by joeyquarters 1
    • initial tweet grabbing

      initial tweet grabbing

      is it possible, to run an inital grabbing, where it tries to get everything back to the first tweet? to avoid ratelimiting, it would be nice to do it "step by step"...

      opened by dd-rx 1
    • Add tweets_to_retrieve option

      Add tweets_to_retrieve option

      This adds support for the count parameter in the statuses/user_timeline api.

      In my testing, I found it was necessary to set this to a higher value than it defaults to in order to get the desired number of tweets to display when excluding both replies and retweets, and the majority of recent tweets being one of those types.

      From the Twitter API Docs: the acount value is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. Retweets are also included in the count, even if include_rts is set false.

      opened by mattpugh 1
    • Update TweetPHP.php to access

      Update TweetPHP.php to access "full_text" parameter

      Use "full_text" parameter if tweet_mode: extended is used. Prevents truncating of tweet.

      See https://stackoverflow.com/questions/38717816/twitter-api-text-field-value-is-truncated

      opened by chriswthomson 0
    • Doesn't appear to cache

      Doesn't appear to cache

      Hi, for some reason the cache file (twiter.txt) appears to be empty, my "cache-dir" is pointing to the cache folder e.g. 'cache_dir' => $base_url . './sites/all/themes/xyz/phpclasses/tweet-php-master/cache/'

      opened by liamraynor 0
    Owner
    Jonathan Nicol
    Jonathan Nicol
    PHP package providing easy and fast access to Twitter API V2.

    Twitter API V2 is a PHP package that provides an easy and fast access to Twitter REST API for Version 2 endpoints.

    Julien SCHMITT 38 Dec 12, 2022
    Twitter REST API for PHP 5.3+

    README The Wid'op Twitter REST library is a modern PHP 5.3+ API allowing you to easily interact with Twitter 1.1. In order to sign your request with t

    Wid'op 24 Aug 10, 2020
    Twitter API for Laravel 5.5+, 6.x, 7.x & 8.x

    Twitter for PHP Twitter API for Laravel 6.x, 7.x, 8.x (and new versions as they are released). Also supports other frameworks via PHP-DI (or feel free

    null 879 Dec 17, 2022
    Get the twitter user authentication keys

    TwitterLogin Get the twitter user authentication keys Step 1: Go to Twitter Developer Portal and Apply to create app. Step 2: Go to app setting and en

    Mohammad Zarchi 1 Nov 21, 2021
    PHP Telegram Bot based on the official Telegram Bot API with iTelegram Class.

    iTelegram PHP Telegram Bot based on the official Telegram Bot API Bots: An introduction for developers Bots are special Telegram accounts designed to

    iNeoTeam | آی نئو 5 Nov 9, 2022
    Simple Google Tts Api Class

    Simple Google Tts Api Class

    Ömer Faruk Demirel 2 Dec 2, 2022
    This app remembers todo list in every specified time (e. every minute, hour, day etc) through telegram bot

    remember_todo_list This app remembers todo list in every specified time (e. every minute, hour, day etc) through telegram bot This project includes tw

    Saidburxon 1 Nov 27, 2021
    A Class Library enabling Asterisk ARI functionality for PHP

    phpari A Class Library enabling Asterisk ARI functionality for PHP Dependencies These are the minimum requirements to have phpari installed on your se

    Nir Simionovich 87 Jan 5, 2023
    PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

    PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

    Sergey Bykov 63 Feb 14, 2022
    A links dashboard which can be integrated via HTML into various other systems.

    quickdash Newest QuickDash version. Combines the API and Client repositories. Requirements PHP version 7.4 - https://www.php.net/ Composer - https://g

    Hugo Soares 0 Aug 11, 2022
    Nexmo REST API client for PHP. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.

    Client Library for PHP Support Notice This library and it's associated packages, nexmo/client and nexmo/client-core have transitioned into a "Maintena

    Nexmo 75 Sep 23, 2022
    OpenAI API Client is a component-oriented, extensible client library for the OpenAI API. It's designed to be faster and more memory efficient than traditional PHP libraries.

    OpenAI API Client in PHP (community-maintained) This library is a component-oriented, extensible client library for the OpenAI API. It's designed to b

    Mounir R'Quiba 6 Jun 14, 2023
    DigitalOcean API v2 client for Symfony and API Platform

    DigitalOcean Bundle for Symfony and API Platform DunglasDigitalOceanBundle allows using the DigitalOcean API from your Symfony and API Platform projec

    Kévin Dunglas 25 Jul 27, 2022
    This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

    This package is a simple API laravel wrapper for Pokemontcg with a sleek Model design for API routes and authentication.

    Daniel Henze 3 Aug 29, 2022
    API SDK for OpenTrade Commerce API: Taobao, Alibaba, JD, 1688, Aliexpress, Ebay.

    OtapiPhpClient Create Client $client = new OtClient($key, $secret, $lang); key (Access Key) secret (Secret for access key) language (2 symbol lang id

    OpenTrade Commerce 5 Sep 20, 2022
    API client for ThePay - payment gate API

    This is the official highly compatible public package of The Pay SDK which interacts with The Pay's REST API. To get started see examples below.

    ThePay.cz s.r.o. 3 Oct 27, 2022
    Code Quiz MonoRepo (API, API Client, App)

    Code Quiz Welcome to the Code Quiz Open Source project from How To Code Well. This is an Open Source project that includes an API and an App for the d

    How To Code Well 2 Nov 20, 2022
    A simple PHP GitHub API client, Object Oriented, tested and documented.

    PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

    KNP Labs 2k Jan 7, 2023
    A PHP library for communicating with the Twilio REST API and generating TwiML.

    twilio-php The default branch name for this repository has been changed to main as of 07/27/2020. Documentation The documentation for the Twilio API c

    Twilio 1.4k Jan 2, 2023