100 free credits. No credit card required. Get a key

How to scrape X (Twitter) user search with PHP

Find X accounts by name, handle or keyword, ranked as X’s People search ranks them, about 20 a page with after for more.

The examples use PHP’s curl extension and json_decode(..., true), so the response is a plain associative array. No Composer packages needed.

GET /v1/x/search/users1 credit per callRefunded on failure

Before you start

  1. Get an API keySign up for 100 free credits, no card. Keys start with gs_live_.
  2. Put it in the environmentEvery example reads it from GROUNDSOCIAL_API_KEY: export GROUNDSOCIAL_API_KEY=gs_live_…
  3. Set up PHPphp -m | grep curl # the curl extension ships with most PHP builds

Call X (Twitter) user search API from PHP

GET /v1/x/search/users. Save this as main.php and run php main.php. It reads the items in data and prints name for each.

main.php
<?php

function groundsocial(string $path, array $params = []): array
{
    $url = 'https://api.groundsocial.dev' . $path . ($params ? '?' . http_build_query($params) : '');
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('GROUNDSOCIAL_API_KEY')],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
    ]);
    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = json_decode($raw, true);
    if ($status !== 200) {
        $e = $data['error'];
        throw new RuntimeException($e['code'] . ': ' . ($e['hint'] ?? $e['message']));
    }
    return $data;
}

$data = groundsocial('/v1/x/search/users', ['q' => 'nasa']);

foreach ($data['data'] as $item) {
    echo $item['name'] ?? '', PHP_EOL;
}

The response

A real X response to this call, recorded from the live source and shortened for display: arrays keep their first items and … marks every cut. The recorded page had 8 items in data. Live calls return current data in the same shape.

200 OK
{
  "data": [
    {
      "id": "11348282",
      "name": "NASA",
      "username": "NASA",
      "description": "Making the seemingly impossible, possible. ✨",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1321163587679784960/0ZxKlEKB_normal.jpg",
      "protected": false,
      "verified": true,
      "verified_type": "government"
    },
    {
      "id": "14091091",
      "name": "Hubble",
      "username": "NASAHubble",
      "description": "The official X account for the NASA Hubble Space Telescope, managed and operated by NASA's Goddard Space Flight Center.",
      "profile_image_url": "https://pbs.twimg.com/profile_images/3468011581/efb985f24af0a814a722457a768f3cc5_normal.jpeg",
      "protected": false,
      "verified": true,
      "verified_type": "government"
    },
    "… 6 more"
  ],
  "meta": {
    "result_count": 8,
    "next_token": "DAAFCgABHX7W7J9__z8LAAIAAADwRW1QQzZ3QUFBZlEvZ0dKTjB2R3AvQUFBQUJRQUFBQUFKYkRRQVFBQUFBQUE1MmcxRVJ1NTByT1ZBQUFBQUFBQUFjRzRJ…"
  }
}

Top-level fields

FieldTypeDescription
dataXUser[]–
metaobject–

Parameters

NameInTypeDescription
q (required)querystringName, handle or keyword. Example: nasa.
afterquerystringCursor: the previous page's meta.next_token.

Pagination

Each page carries the next cursor in meta.next_token; pass it back as after and stop when it is empty. Every page is a separate call at 1 credit per call, so cap the pages you read. It reuses groundsocial() from the script above.

Every page
$params = ['q' => 'nasa'];
for ($i = 0; $i < 5; $i++) { // each page is one call
    $page = groundsocial('/v1/x/search/users', $params);
    foreach ($page['data'] ?? [] as $item) {
        echo $item['name'] ?? '', PHP_EOL;
    }
    $cursor = $page['meta']['next_token'] ?? null;
    if (!$cursor) break;
    $params['after'] = $cursor;
}

Errors and retries

Every error is JSON with error.code (stable: branch on it), message, hint (what to do next), docs_url and retryable. A failed call is never charged. Retry only when retryable is true, after the Retry-After header.

Errors
try {
    $data = groundsocial('/v1/x/search/users', ['q' => 'nasa']);
} catch (RuntimeException $e) {
    // "code: hint", e.g. "target_not_found: ..." (never charged).
    fwrite(STDERR, $e->getMessage() . PHP_EOL);
    exit(1);
}
StatusMeaning
200Matching accounts, with a next_token.
400Invalid input. Nothing was charged.
401Missing or invalid API key.
402Not enough credits, a spend cap was reached, or payment is required.
403The target is private, or the account is suspended.
404The post or account does not exist, was deleted, or is suspended.
429Too many requests. Wait for Retry-After seconds.
503X is temporarily unavailable. Retryable; nothing was charged.

Every error code and what to do about it.

Pricing

Cost
Per call1 credit per call
1,000 calls$1.00 on the starter pack, $0.40 at volume
No key (MPP or x402)$0.01 per call
Failed callRefunded, never charged

Every response has x-credits-charged and x-credits-remaining headers. Credits never expire. Packs and calculator.

From an AI agent (MCP)

The same call is the x_search_users tool on the hosted MCP server, so Claude, Cursor or any MCP client can make it without code. Add the server once:

bash
claude mcp add --transport http groundsocial https://api.groundsocial.dev/mcp

Then ask for it in words (“X accounts matching a name, handle or keyword, paginated”), or call the tool directly:

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "x_search_users",
    "arguments": {
      "q": "nasa"
    }
  }
}

MCP setup for Claude Desktop, Cursor, VS Code and ChatGPT.

Find the official account

Search the brand name and keep results with verified_type business or government, then call x_user_get for follower counts.

Questions

Are follower counts included?

No, X’s search results carry the profile basics only. Call x_user_get on the accounts you keep.

Keep going

Run it on your own data

One key for X and 76 more platforms, over REST or MCP. Free credits on signup, no card.

X is a trademark of X Corp. We are not affiliated with or endorsed by X Corp.