Twitter (X) API in PHP: a Guzzle client with safe decoding and cursor paging

By TwitterAPI.io Team•12 min read
Diagram mapping TwitterAPI.io JSON fields to PHP handling: a 19-digit string id kept as a string with JSON_BIGINT_AS_STRING, UTF-8 text handled with mb_strlen and mb_substr, entities.urls defaulted with ?? [], extendedEntities.media checked with isset, and has_next_page with next_cursor consumed by a Generator, each with its measured share.
The JSON-to-PHP decoding map this guide builds, checked on 445 real tweets collected in 2026.
TL;DR
  • No SDK needed: one shared Guzzle Client with base_uri, an X-API-Key header and timeouts reaches every read endpoint; a plain ext-curl version and a Laravel Http:: version are included too.
  • Ids stay strings: all 445 tweet ids in our sample were 19-digit JSON strings above 2^53 and 0 exceeded PHP_INT_MAX; JSON_BIGINT_AS_STRING is the safety net for any numeric id field.
  • Text is multibyte: 55.1% of tweets had non-ASCII characters and 33.0% had emoji, with up to 49 more bytes than characters in one post, so truncate with mb_substr, not substr.
  • Pages are big and uneven: a full 20-tweet page was a median 200,196 bytes of JSON (re-serialized, about 10,010 per tweet), and 6 of 23 pages held fewer than 20 tweets while has_next_page was still true.
  • Retries are a loop: retry HTTP 429, 502 and 503 with exponential backoff and jitter, read detail on HTTP 400 and msg when a 200 response says status: error.
  • Cost: $0.15 per 1,000 tweets returned on TwitterAPI.io versus $0.005 per post read ($5 per 1,000) on X's pay-per-usage rate card, about 33x.

Search for a PHP Twitter API example and the results split into two piles: OAuth tutorials for X's own API (consumer keys, access tokens, abraham/twitteroauth) and wrappers that were written for the v1.1 API many years ago. Both assume an X developer account. Neither shows what a tweet looks like once json_decode has turned it into a PHP array, which is where real bugs come from: an id that silently becomes a float, a preview that cuts an emoji in half, a foreach over an entities key that is not there, a paging loop that stops on a short page.

This guide builds a small, typed PHP 8.1+ client for TwitterAPI.io with Guzzle: one shared client, a request method with retries and readable errors, a Generator that walks cursor pages, and decoding helpers for ids, multibyte text, entities and dates. Each decoding choice is backed by a measurement on 445 real posts from 7 PHP-ecosystem organization accounts (@WordPress, @symfony, @laravelnews, @drupal, @packagist, @phpstorm and @official_php). The PHP on this page was not executed here; its syntax follows the php.net and Guzzle documentation, and the numbers come from the same API responses your code will receive.

Tweets in our 445-post PHP sample where strlen and mb_strlen disagree

55.1%

01 — Section

Which Twitter (X) API a PHP app calls, and what that changes

There are two different APIs behind the phrase "Twitter API PHP". X's official API lives at api.x.com under /2/... paths, requires a developer account and an app, signs requests with OAuth 2.0 bearer tokens or OAuth 1.0a user context, and bills on X's pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing). TwitterAPI.io is a separate service at api.twitterapi.io with paths such as /twitter/user/info and /twitter/tweet/advanced_search; reads use one API key in an X-API-Key header, and no X account is needed.

The PHP libraries you will find target the first one. abraham/twitteroauth is the long-running community library for X's OAuth API: its GitHub repository is active and not archived, and Packagist lists version 9.0.0 from November 2026 with a PHP ^8.3 requirement. It is a good fit if you hold X API credentials and need user-context OAuth. It does not speak to TwitterAPI.io, and for plain reads it brings an OAuth setup you do not need.

Against TwitterAPI.io a library is optional: the protocol is HTTPS with JSON, so a client is about 120 lines of PHP on top of Guzzle, or 30 lines on top of ext-curl. The rest of this page builds it in order: the shared client with retries, decoding helpers, a paging Generator, a short program, the no-Composer version, and a Laravel service.

X official APITwitterAPI.io
Host and pathsapi.x.com with /2/tweets style pathsapi.twitterapi.io with /twitter/user/info style paths
AuthOAuth 2.0 bearer or OAuth 1.0a, developer appone key in X-API-Key
Reading posts$0.005 per post read$0.15 per 1,000 tweets returned
PHP libraryabraham/twitteroauth (9.0.0, PHP 8.3+)none needed: Guzzle or ext-curl
02 — Section

Set up one Guzzle client with retries and readable errors

Install Guzzle with composer require guzzlehttp/guzzle. Packagist lists the 8.x line as current (8.5.5) and its constraint accepts PHP ^7.4 || ^8.0; the class below uses only APIs that exist in both Guzzle 7 and 8: the Client constructor options base_uri, headers, connect_timeout, timeout and http_errors, $client->get($path, ['query' => ...]), the TransferException base class, and the PSR-7 response methods (the request-options page at docs.guzzlephp.org documents the 7.x line). Create the client once (in a container, a static, or a long-lived worker) so the key, the base URI and the timeouts live in one place.

Why http_errors => false. By default Guzzle throws ClientException on 4xx and ServerException on 5xx. Turning that off lets one code path read the status: 429, 502 and 503 are retried with exponential backoff plus jitter (and a Retry-After header is honored if one is present), a 400 surfaces the detail text that names the missing or invalid parameter, and any other non-200 surfaces msg. Only transport failures (DNS, TLS, timeouts) arrive as an exception, a TransferException,, and they are retried the same way.

The 200 that is an error. Some failures come back as HTTP 200 with status: "error" and a msg; an unknown account on /twitter/user/info returns msg: "user not found" and data: null rather than a 404. The client checks status on every response, so a caller never mistakes an error body for an empty result. Retries are a plain for loop with usleep, which is easy to read and to test; Guzzle's retry middleware is an alternative if you already use a handler stack.

php
<?php
// composer require guzzlehttp/guzzle   (works with Guzzle 7 and 8)
declare(strict_types=1);

namespace App\TwitterApi;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\TransferException;
use Psr\Http\Message\ResponseInterface;

final class TwitterApiException extends \RuntimeException {}

final class TwitterApiClient
{
    private Client $http;

    public function __construct(string $apiKey, private int $maxAttempts = 4)
    {
        // One client for the whole process: it keeps the base URI, the key header and the timeouts.
        $this->http = new Client([
            'base_uri'        => 'https://api.twitterapi.io',
            'headers'         => ['X-API-Key' => $apiKey, 'Accept' => 'application/json'],
            'connect_timeout' => 10,
            'timeout'         => 40,
            'http_errors'     => false,   // we read the status code ourselves
        ]);
    }

    /** @return array<string, mixed> decoded JSON body */
    public function get(string $path, array $query = []): array
    {
        for ($attempt = 1; ; $attempt++) {
            try {
                $res = $this->http->get($path, ['query' => $query]);
            } catch (TransferException $e) {          // DNS, TLS, timeout: no HTTP response at all
                if ($attempt >= $this->maxAttempts) {
                    throw new TwitterApiException('network error: ' . $e->getMessage(), 0, $e);
                }
                usleep($this->backoffMs($attempt) * 1000);
                continue;
            }

            $status = $res->getStatusCode();
            if (($status === 429 || $status === 503 || $status === 502) && $attempt < $this->maxAttempts) {
                usleep($this->backoffMs($attempt, $res) * 1000);
                continue;
            }

            $body = $this->decode($res);
            if ($status !== 200) {
                // HTTP 400 for a missing or invalid parameter carries the text in "detail"
                $why = $body['detail'] ?? $body['msg'] ?? 'no message';
                throw new TwitterApiException(
                    sprintf('HTTP %d on %s: %s', $status, $path, is_string($why) ? $why : json_encode($why)),
                    $status
                );
            }
            if (($body['status'] ?? null) === 'error') {      // HTTP 200 with status "error", e.g. user not found
                throw new TwitterApiException((string) ($body['msg'] ?? 'unknown error'), $status);
            }
            return $body;
        }
    }

    /** @return array<string, mixed> */
    private function decode(ResponseInterface $res): array
    {
        $raw = (string) $res->getBody();
        if ($raw === '') {
            return [];
        }
        try {
            $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
        } catch (\JsonException $e) {
            throw new TwitterApiException('response was not JSON (HTTP ' . $res->getStatusCode() . ')', $res->getStatusCode(), $e);
        }
        return is_array($data) ? $data : [];
    }

    private function backoffMs(int $attempt, ?ResponseInterface $res = null): int
    {
        $retryAfter = $res?->getHeaderLine('Retry-After') ?? '';
        if (ctype_digit($retryAfter)) {
            return min((int) $retryAfter, 60) * 1000;    // honor the server's hint when it sends one
        }
        return 500 * (2 ** ($attempt - 1)) + random_int(0, 250);   // 0.5 s, 1 s, 2 s ... plus jitter
    }
}
03 — Section

Decode tweets safely: ids, multibyte text, entities and dates

json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING) gives associative arrays, throws a JsonException instead of returning null on bad input, and keeps any integer too large for PHP's int as a string. In our sample every tweet id already arrived as a JSON string: 445 of 445 ids were 19 digits long, all of them above 2^53 (the limit for an exact float, and the reason a JavaScript front end must never see them as numbers), and 0 above PHP_INT_MAX (9,223,372,036,854,775,807 on 64-bit builds). So the flag is a safety net, and the rule is simple: never cast an id with (int) or (float), store it in a VARCHAR(20) or BIGINT UNSIGNED column, and compare ids as strings.

Text is multibyte. 55.1% of the 445 texts contained at least one non-ASCII character, which means strlen() (bytes) and mb_strlen() (characters) disagree; among the account's own posts, excluding reposts, the share was 43.5%. 33.0% contained emoji. The median gap on an affected post was 3 bytes, the 95th percentile across all posts 13, and the largest 49. That gap is why substr($text, 0, 80) can end in half a character and produce invalid UTF-8 that a later json_encode refuses; mb_substr with an explicit 'UTF-8' cannot.

Entity arrays are often empty. 63.6% of tweets had at least one item in entities.urls, 53.7% in entities.user_mentions, 32.4% in entities.hashtags, and 26.7% in extendedEntities.media. The largest counts in one tweet were 3 urls, 5 hashtags, 9 mentions and 4 media items, so these arrays are small, but code must default missing keys with ?? [] before a foreach. Use expanded_url for links, because url is the shortened t.co form.

Reposts wrap the original. 26.1% of the sample were reposts. Their text starts with RT @ and is often truncated, while the full original sits under retweeted_tweet; read from there when you display or index content. createdAt uses the format Thu Oct 01 13:03:04 +0000 2026, which DateTimeImmutable::createFromFormat('D M d H:i:s O Y', ...) parses.

php
<?php
declare(strict_types=1);

// Ids arrive as JSON strings ("1975..." with 19 digits). Keep them as strings:
// (float) or a JS-style number would round them, and you never do math on an id.
function tweetId(array $t): string
{
    return (string) $t['id'];
}

// strlen() counts bytes, mb_strlen() counts characters. Truncate with mb_* or you can
// cut an emoji or an accented letter in half and produce invalid UTF-8.
function preview(array $t, int $max = 80): string
{
    $text = (string) ($t['text'] ?? '');
    return mb_strlen($text, 'UTF-8') > $max
        ? mb_substr($text, 0, $max - 3, 'UTF-8') . '...'
        : $text;
}

// Entity arrays can be empty, and extendedEntities often has no "media" key at all.
function expandedUrls(array $t): array
{
    return array_values(array_filter(array_map(
        fn (array $u): string => (string) ($u['expanded_url'] ?? $u['url'] ?? ''),
        $t['entities']['urls'] ?? []
    )));
}

function mediaUrls(array $t): array
{
    return array_map(
        fn (array $m): string => (string) ($m['media_url_https'] ?? ''),
        $t['extendedEntities']['media'] ?? []
    );
}

// createdAt looks like "Thu Oct 01 13:03:04 +0000 2026"
function createdAt(array $t): \DateTimeImmutable
{
    $dt = \DateTimeImmutable::createFromFormat('D M d H:i:s O Y', (string) $t['createdAt']);
    if ($dt === false) {
        throw new \UnexpectedValueException('unexpected createdAt: ' . $t['createdAt']);
    }
    return $dt;
}

// A repost carries the original under retweeted_tweet; its text starts with "RT @".
function original(array $t): array
{
    return is_array($t['retweeted_tweet'] ?? null) ? $t['retweeted_tweet'] : $t;
}
Horizontal bar chart of 445 tweets: 55.1% have non-ASCII text, 33.0% emoji, 63.6% urls, 53.7% mentions, 32.4% hashtags, 26.7% media, and 100.0% have ids above 2^53.
What a decoded tweet carries, measured on 445 posts from 7 PHP-ecosystem organization accounts, collected in 2026.
04 — Section

Page through timelines and search with a Generator

Both tweet endpoints return a page of results plus has_next_page and next_cursor; you pass the cursor back as cursor to get the next page. A PHP Generator turns that into a stream you can foreach over, and it fetches the next page only when the caller asks for more tweets, so break after ten results costs one request, not five.

Loop on has_next_page, not on the page size. In our sample 6 of 23 pages held fewer than 20 tweets (the smallest held 14) while has_next_page was still true. A loop that stops when a page has fewer than 20 items would have quit early on those accounts.

Do not yield from the page array. yield from $tweets keeps the array keys, so every page yields keys 0 to 19 again, and iterator_to_array($gen) silently overwrites earlier tweets with later ones. Yield each tweet in a foreach, or call iterator_to_array($gen, false).

Mind memory on long runs. A full 20-tweet page was a median 200,196 bytes and up to 246,892 bytes when we re-serialized it as UTF-8 JSON (that is not the compressed wire size), so about 10,010 bytes per tweet before PHP's array overhead. The Generator holds one page at a time; collecting thousands of full tweet arrays into one variable is what exhausts memory_limit, so keep only the fields you need.

php
<?php
// Add these methods to TwitterApiClient.

/**
 * Yield tweets one by one across pages until has_next_page is false or $maxPages is reached.
 * @return \Generator<int, array<string, mixed>>
 */
private function pages(string $path, array $query, bool $underData, int $maxPages): \Generator
{
    $cursor = null;
    for ($page = 0; $page < $maxPages; $page++) {
        $body = $this->get($path, $cursor === null ? $query : $query + ['cursor' => $cursor]);
        $tweets = $underData ? ($body['data']['tweets'] ?? []) : ($body['tweets'] ?? []);
        foreach ($tweets as $tweet) {
            yield $tweet;          // not "yield from $tweets": that reuses keys 0-19 on every page
        }
        // Never stop on a short page: pages can hold fewer than 20 tweets and still have a next page.
        if (empty($body['has_next_page']) || empty($body['next_cursor'])) {
            return;
        }
        $cursor = (string) $body['next_cursor'];
    }
}

/** Newest posts of one account; /twitter/user/last_tweets nests them under data.tweets. */
public function timeline(string $userName, int $maxPages = 3): \Generator
{
    return $this->pages('/twitter/user/last_tweets', ['userName' => $userName], true, $maxPages);
}

/** Search with X operators; /twitter/tweet/advanced_search returns tweets at the top level. */
public function search(string $query, string $queryType = 'Latest', int $maxPages = 3): \Generator
{
    return $this->pages('/twitter/tweet/advanced_search', ['query' => $query, 'queryType' => $queryType], false, $maxPages);
}

/** One profile; /twitter/user/info returns it under data. */
public function user(string $userName): array
{
    return $this->get('/twitter/user/info', ['userName' => $userName])['data'] ?? [];
}
05 — Section

Use the client: a profile, a timeline and a search in one script

The script below reads the key from the environment, prints one profile, the latest page of one timeline with dates and safe previews, and two pages of a search. The search query uses X's own operators (OR, lang:en, -filter:retweets, from:), which /twitter/tweet/advanced_search accepts with queryType set to Latest or Top.

Errors arrive as one exception type with the HTTP status as its code, so a cron job can log and exit non-zero, and a web request can map a 400 to a validation message. Named arguments (maxPages: 1), constructor property promotion and the nullsafe operator used in the client need PHP 8.0 or later; this page targets PHP 8.1 and newer.

Each tweet returned costs 15 credits ($0.00015), so the printed cost line is a quick sanity check while you develop.

php
<?php
// php demo.php     (TWITTERAPI_IO_KEY set in the environment)
declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use App\TwitterApi\TwitterApiClient;
use App\TwitterApi\TwitterApiException;

$key = getenv('TWITTERAPI_IO_KEY') ?: exit("set TWITTERAPI_IO_KEY\n");
$api = new TwitterApiClient($key);

try {
    $profile = $api->user('laravelphp');
    printf("@%s  %s followers\n", $profile['userName'] ?? '?', number_format((int) ($profile['followers'] ?? 0)));

    foreach ($api->timeline('symfony', maxPages: 1) as $t) {
        printf("%s  %s  %s\n", createdAt($t)->format('Y-m-d'), tweetId($t), preview(original($t), 70));
    }

    $count = 0;
    foreach ($api->search('(laravel OR symfony) lang:en -filter:retweets', 'Latest', maxPages: 2) as $t) {
        $count++;
        foreach (expandedUrls($t) as $url) {
            echo "  link: $url\n";
        }
    }
    printf("%d search results, about $%.4f at 15 credits per tweet\n", $count, $count * 0.00015);
} catch (TwitterApiException $e) {
    fwrite(STDERR, "API error ({$e->getCode()}): {$e->getMessage()}\n");
    exit(1);
}
06 — Section

No Composer: the same call with ext-curl

Shared hosting, a WordPress plugin, or a one-file script may not have Composer. ext-curl is enough: build the URL with http_build_query, send the X-API-Key header, and decode with the same flags. file_get_contents with a stream context also works, but it hides the status code in $http_response_header, so curl is the clearer choice.

Keep the same three checks as the Guzzle client: a non-200 status, a 200 with status: "error", and a decode failure. Add the retry loop from above if the script runs unattended.

php
<?php
// No Composer: only ext-curl and ext-json (bundled since PHP 8.0) are needed.
declare(strict_types=1);

function twitterapi_get(string $path, array $query, string $key): array
{
    $ch = curl_init('https://api.twitterapi.io' . $path . '?' . http_build_query($query));
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['X-API-Key: ' . $key, 'Accept: application/json'],
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 40,
    ]);
    $raw = curl_exec($ch);
    if ($raw === false) {
        throw new RuntimeException('curl: ' . curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $body = json_decode($raw, true, 512, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
    if ($status !== 200 || ($body['status'] ?? null) === 'error') {
        throw new RuntimeException("HTTP $status: " . json_encode($body['detail'] ?? $body['msg'] ?? null));
    }
    return $body;
}

$key = getenv('TWITTERAPI_IO_KEY') ?: exit("set TWITTERAPI_IO_KEY\n");
$body = twitterapi_get('/twitter/tweet/advanced_search', ['query' => 'from:official_php', 'queryType' => 'Latest'], $key);
foreach ($body['tweets'] ?? [] as $t) {
    echo $t['id'], '  ', mb_substr($t['text'] ?? '', 0, 60, 'UTF-8'), PHP_EOL;
}
07 — Section

Twitter API in Laravel with the Http facade

Laravel's HTTP client wraps Guzzle, so the same calls fit a service class. The Laravel 13.x documentation covers each method used here: Http::withHeaders, acceptJson, connectTimeout, retry($times, $sleepMilliseconds, $when) with a closure that receives the exception and the pending request, and ->throw()->json(). Keep the key in .env and read it through config/services.php, so config:cache still works.

The retry closure limits retries to throttling, 5xx and network failures; without it Laravel would also retry a 400 that will never succeed. As with the plain client, check status in the body, because an error can arrive with HTTP 200. For scheduled reads, put the call in a queued job or a scheduled command rather than a web request.

php
<?php
// config/services.php:  'twitterapi' => ['key' => env('TWITTERAPI_IO_KEY')],
namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;

final class TwitterApi
{
    private function client(): PendingRequest
    {
        return Http::withHeaders(['X-API-Key' => config('services.twitterapi.key')])
            ->acceptJson()
            ->connectTimeout(10)
            ->timeout(40)
            // retry 3 times, 500 ms apart, but only on throttling, 5xx or network errors
            ->retry(3, 500, function (\Throwable $e, PendingRequest $request): bool {
                return $e instanceof ConnectionException
                    || ($e instanceof RequestException && in_array($e->response->status(), [429, 502, 503], true));
            });
    }

    /** @return array<int, array<string, mixed>> */
    public function search(string $query): array
    {
        $body = $this->client()
            ->get('https://api.twitterapi.io/twitter/tweet/advanced_search', ['query' => $query, 'queryType' => 'Latest'])
            ->throw()
            ->json();

        if (($body['status'] ?? null) === 'error') {
            throw new \RuntimeException($body['msg'] ?? 'twitterapi.io error');
        }
        return $body['tweets'] ?? [];
    }
}
08 — Section

How often PHP-ecosystem accounts post, and what reading them costs

The same sample answers an operational question: if your PHP app watches these accounts, how much is there to fetch? Not much. The busiest, @symfony, posted 1.96 times a day in its sampled window; @official_php posted 0.04 times a day. Even the busiest account would leave the large majority of five-minute polls empty.

AccountPosts in sampleDays coveredPosts per dayReposts
@symfony20101.960%
@laravelnews100591.696%
@WordPress20141.410%
@phpstorm501200.4236%
@drupal1007240.1425%
@packagist1008060.1258%
@official_php5513410.0416%

That matters for cost because an empty check is still billed the 15-credit minimum, $0.00015. Polling one account every five minutes for a month is 8,640 checks, about $1.30 in minimums before any tweet is returned; every 60 seconds it is 43,200 checks, $6.48. For several quiet accounts, one /twitter/tweet/advanced_search query that combines them (from:symfony OR from:laravelnews OR from:drupal) costs the same per check as a single account, and the tweets it returns are billed at $0.15 per 1,000.

TwitterAPI.io bills per result: 15 credits per tweet returned, which is $0.15 per 1,000 tweets, with a 15-credit ($0.00015) minimum on a request that returns nothing; profiles are 18 credits each ($0.18 per 1,000), and follower or following lists are 1 to 3 credits per user returned. X's pay-per-usage rate card lists $0.005 per post read, $0.010 per user read and $0.010 per follower or following read, with post reads capped at 3 million per monthly billing cycle before Enterprise. Per 1,000 tweets that is $5 against $0.15, about 33x.

New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days). Purchased credits never expire, and subscription plans (Starter $29, Builder $99, Pro $199, Scale $499, Business $1,499 a month) are on the pricing page linked below. Rate limits are 0.2 requests per second before the first payment and 20 once paid, which is why the client backs off on 429.

Writing from PHP. Posting, liking, retweeting, following and media upload are available too, through an authenticated session rather than the API key alone: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, and each write such as /twitter/create_tweet_v2 or /twitter/follow_user_v2 then costs 60 credits ($0.0006), billed per HTTP 200 call. Every write acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace and expect the session to need a fresh login from time to time. The Guzzle client above sends those as POST requests with a JSON body.

Horizontal bar chart of posts per day for seven PHP-ecosystem accounts: @symfony 1.96, @laravelnews 1.69, @WordPress 1.41, @phpstorm 0.42, @drupal 0.14, @packagist 0.12, @official_php 0.04.
Posting cadence of 7 PHP-ecosystem organization accounts in their sampled windows, 445 posts collected in 2026.
09 — Section

How we collected this

Question. What does PHP's JSON decoding actually have to handle on recent posts: the share of texts where strlen and mb_strlen disagree, emoji, the size of each entity array, the size of a 20-tweet page, whether any id exceeds PHP_INT_MAX, and how often PHP-ecosystem accounts post?

Accounts. 7 public organization accounts: @WordPress, @symfony, @laravelnews, @drupal, @packagist, @phpstorm and @official_php. @laravelphp and @composerphp returned no posts from /twitter/user/last_tweets and were excluded.

Method and window. /twitter/user/last_tweets with default settings, newest first, one to five pages per account, deduplicated by id: 445 posts on 23 pages, 17 of them full 20-tweet pages. Each account's window runs from its oldest to newest post in the sample, from 10 days for @symfony to about 1,340 days for @official_php. Collected in 2026 with about 40 requests, costing about $0.07. Byte counts treat text as UTF-8 (strlen) and characters as Unicode code points (mb_strlen); page sizes are the response body re-serialized as UTF-8 JSON, not the bytes on the wire. The PHP code on this page was not executed for this study (no PHP runtime in our collection environment); the Python script below reruns the same checks on any account.

What the sample cannot show. 445 posts from 7 accounts is a small, English-leaning sample: two accounts contributed only one page each because the timeline endpoint returned errors for further pages during collection. Accounts that post in other scripts will show higher non-ASCII and byte-gap figures, and media-heavy accounts larger pages. The cadence table describes each account's recent past, not a forecast.

Privacy. Aggregates only, organization accounts only; reposted, quoted and mentioned authors are not analyzed. Raw timeline pages are kept in the repository only for accounts whose pages contain no other authors.

python
"""check_php_decoding.py - pull a few timeline pages from TwitterAPI.io and report the facts
that decide your PHP decoding code: share of tweets where strlen != mb_strlen, emoji share,
entity array sizes, page size in bytes, and tweet ids above 2^53 / PHP_INT_MAX.

    pip install requests
    export TWITTERAPI_IO_KEY=...      # from the twitterapi.io dashboard
    python check_php_decoding.py laravelnews
"""
import json
import os
import re
import sys

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
PHP_INT_MAX = 2**63 - 1
EMOJI = re.compile("[\U0001F000-\U0001FAFF\u2600-\u27BF]")


def pages(user_name, max_pages=3):
    cursor = None
    for _ in range(max_pages):
        params = {"userName": user_name}
        if cursor:
            params["cursor"] = cursor
        r = requests.get(f"{BASE}/twitter/user/last_tweets", headers=HEADERS, params=params, timeout=40)
        r.raise_for_status()
        body = r.json()
        if body.get("status") == "error":
            raise SystemExit(body.get("msg"))
        yield body
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]


def main():
    user = sys.argv[1] if len(sys.argv) > 1 else "laravelnews"
    tweets, sizes = [], []
    for body in pages(user):
        batch = (body.get("data") or {}).get("tweets", [])
        tweets.extend(batch)
        sizes.append((len(batch), len(json.dumps(body, ensure_ascii=False).encode("utf-8"))))
    if not tweets:
        raise SystemExit("no tweets returned")
    n = len(tweets)
    texts = [t.get("text") or "" for t in tweets]
    non_ascii = sum(len(s.encode("utf-8")) != len(s) for s in texts)
    print(f"{n} tweets from @{user}")
    print(f"  strlen != mb_strlen: {non_ascii} ({100 * non_ascii / n:.1f}%)")
    print(f"  with emoji: {sum(bool(EMOJI.search(s)) for s in texts)}")
    print(f"  largest byte-char gap: {max(len(s.encode('utf-8')) - len(s) for s in texts)} bytes")
    for key in ("urls", "hashtags", "user_mentions"):
        counts = [len((t.get("entities") or {}).get(key) or []) for t in tweets]
        print(f"  entities.{key}: {sum(c > 0 for c in counts)} non-empty, max {max(counts)}")
    media = [len((t.get("extendedEntities") or {}).get("media") or []) for t in tweets]
    print(f"  extendedEntities.media: {sum(c > 0 for c in media)} non-empty")
    ids = [int(t["id"]) for t in tweets]
    print(f"  id JSON type: {type(tweets[0]['id']).__name__}; above 2^53: {sum(i > 2**53 for i in ids)}; "
          f"above PHP_INT_MAX: {sum(i > PHP_INT_MAX for i in ids)}")
    for count, size in sizes:
        print(f"  page with {count} tweets: {size:,} bytes re-serialized as UTF-8 JSON")
    print(f"  cost: about ${n * 0.00015:.4f} at 15 credits per tweet returned")


if __name__ == "__main__":
    main()

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Is there a PHP SDK for the Twitter (X) API?

The widely used PHP library for X's API is the community-maintained abraham/twitteroauth (Packagist 9.0.0, November 2026, PHP 8.3+), which targets X's own OAuth-protected API and X's pricing. For TwitterAPI.io you need no SDK: Guzzle or ext-curl plus json_decode is enough, as shown on this page.

Does abraham/twitteroauth work with TwitterAPI.io?

No. TwitterOAuth signs requests for X's official API at api.x.com with OAuth credentials from an X developer app. TwitterAPI.io uses one API key in an X-API-Key header and its own paths such as /twitter/user/last_tweets, so a plain HTTP client is the right tool.

How do I get tweets from a user in PHP?

Send GET /twitter/user/last_tweets?userName=<handle> to https://api.twitterapi.io with your key in X-API-Key. The tweets are under data.tweets, 20 or fewer per page; pass next_cursor back as cursor while has_next_page is true. The timeline() Generator on this page wraps exactly that.

Why do tweet ids break in PHP or JavaScript?

Tweet ids are 19-digit numbers above 2^53, so any float conversion rounds them. In our 445-tweet sample every id arrived as a JSON string, which is safe as long as you never cast it. PHP's 64-bit int holds them (0 exceeded PHP_INT_MAX), but a JavaScript front end does not, so keep them as strings end to end and decode with JSON_BIGINT_AS_STRING.

Should I use strlen or mb_strlen for tweet text?

mb_strlen with 'UTF-8'. In our sample 55.1% of tweets contained non-ASCII characters, where strlen counts more bytes than there are characters (up to 49 extra bytes in one post). Use mb_substr for previews so you never cut a character in half.

How do I use the Twitter API in Laravel?

Use the built-in HTTP client: Http::withHeaders(['X-API-Key' => config('services.twitterapi.key')])->acceptJson()->retry(3, 500, $when)->get('https://api.twitterapi.io/twitter/tweet/advanced_search', [...])->throw()->json(). Limit retries to 429, 5xx and connection errors, and check the body's status field.

How much does reading tweets from PHP cost?

TwitterAPI.io charges 15 credits per tweet returned, $0.15 per 1,000 tweets, with a 15-credit ($0.00015) minimum on a request that returns nothing. X's pay-per-usage rate card lists $0.005 per post read, $5 per 1,000. New accounts that pass the automatic bot check get up to $1 of free credits (up to 100,000 credits, no card, one per person or network, expiring after 31 days).

Can PHP post tweets through TwitterAPI.io?

Yes, through an authenticated session: one /twitter/user_login_v2 call ($0.10, with a proxy you supply) returns login_cookies, then each write such as /twitter/create_tweet_v2 costs 60 credits ($0.0006), billed per HTTP 200 call. The write acts as that X account, so X can rate-limit, lock or suspend it; keep a human pace.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.