Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP - Fetch Latest Tweets of Specific User

The following tutorial will teach you how to fetch the latest tweets of a specific user, through the use of the Twitter API. This is probably most useful for your own organization's site to be automatically showing your latest tweets somewhere.

Steps

First, you need to create a Twitter developer account. It's free, but you have to go through quite a lot of steps. Luckily the linked tutorial guides you right through it.

Secondly, we need to install the guzzle-wrapper package that makes sending API requests a doddle.

composer require programster/guzzle-wrapper

Then, all we really need is the following code:

<?php

require_once(__DIR__ . '/vendor/autoload.php');


/**
 * Fetch tweets from a user's timeline. For full details of the endpoint, go to:
 * https://developer.twitter.com/en/docs/twitter-api/v1/tweets/timelines/api-reference/get-statuses-user_timeline
 * @param int $numTweets - the number of tweets to fetch. Can't be larger than 200
 * @param string $twitterUsername - the username of the twitter account you wish to get the latest tweets of.
 * @param string $authToken - your bearer auth token. If you don't know it then use the getBearerToken() method with
 * your key and secret.
 * @return array - a collection of tweet response objects (in array format)
 */
function getTweets(int $numTweets, string $twitterUsername, string $authToken) : array
{
    $parameters = array(
        'screen_name' => $twitterUsername,
        'count' => $numTweets,
    );

    $headers = array(
        'Authorization' => 'Bearer ' . $authToken
    );

    $request = new Programster\GuzzleWrapper\Request(
        Programster\GuzzleWrapper\Method::createGet(),
        $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json',
        $parameters,
        $headers,
        $useFormParams=false
    );

    $response = $request->send();
    $responseBody = $response->getBody();
    $responseBodyArray = json_decode($responseBody, true);
    return $responseBodyArray;
}

... which you can use it like so:

$tweets = getTweets(3, "Programster_UK", $bearerToken);

foreach ($tweets as $tweetArray)
{
    $timestamp = strtotime($tweetArray['created_at']);
    $dateString = date('l jS F Y', $timestamp);
    $message = $tweetArray['text'];
    print "{$dateString} : {$message}" . PHP_EOL;
}

That will output something like:

Sunday 21st February 2021 : Can deploy through #docker https://t.co/V7BpCdHOdj
Sunday 21st February 2021 : I recently got back into #Seafile again and really pleased to see that the free/core version now supports syncing o… https://t.co/cNdcbE7Qen
Friday 22nd January 2021 : @danpcotton @linuxtoday awwww shucks.

Perhaps one day I can be bothered to make a proper SDK, but for now this will have to do.

Fetch Your Bearer Token

If you need to look up your bearer token again, you can use this function:

/**
 * Fetches your bearer token, using your api key and secret
 * @param string $apiKey - your twitter API key
 * @param string $apiSecret - yoour twitter API secret
 * @return string - your bearer auth token that you need for authenticating most requests.
 */
function getBearerToken(string $apiKey, string $apiSecret) : string
{
    $parameters = array(
        'grant_type' => "client_credentials",
    );

    $headers = array(
        'Authorization' => 'Basic ' . base64_encode("{$apiKey}:{$apiSecret}"),
    );

    $request = new Programster\GuzzleWrapper\Request(
        Programster\GuzzleWrapper\Method::createPost(),
        $url = 'https://api.twitter.com/oauth2/token',
        $parameters,
        $headers,
        $useFormParams=true
    );

    $response = $request->send();
    $responseBody = $response->getBody();
    $responseBodyArray = json_decode($responseBody, true);
    return $responseBodyArray['access_token'];
}
Last updated: 27th February 2021
First published: 27th February 2021