How to use a Google Search API in PHP (with full code)
This guide gets live Google results into PHP with cURL, no packages needed. It uses the SerpWiz Google Search API and works on PHP 8.
1. Get an API key
Create a free account (1,000 free queries a month, no card), then create a key under API keys in the dashboard. Put it in an environment variable, SERPWIZ_API_KEY, rather than in your code.
2. A search function with retries
Failed requests are free, so the function retries 429, 502 and 503 responses after the Retry-After header:
<?php
function serpwiz(string $endpoint, array $params, int $attempts = 3): array
{
$url = 'https://api.serpwiz.com/v1/' . $endpoint . '?' . http_build_query($params);
for ($i = 0; $i < $attempts; $i++) {
$retryAfter = 1;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('SERPWIZ_API_KEY')],
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$retryAfter) {
if (stripos($line, 'Retry-After:') === 0) $retryAfter = max(1, (int) trim(substr($line, 12)));
return strlen($line);
},
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if (in_array($status, [429, 502, 503], true)) { sleep($retryAfter); continue; }
$data = json_decode((string) $body, true);
if ($status !== 200) throw new RuntimeException($data['error']['message'] ?? "HTTP $status");
return $data;
}
throw new RuntimeException("Gave up after $attempts attempts");
}
3. Your first search
$data = serpwiz('google/search', ['q' => 'best crm for startups', 'gl' => 'us', 'hl' => 'en']);
foreach ($data['results'] as $r) {
echo $r['position'], ' ', $r['title'], ' ', $r['url'], PHP_EOL;
}
Each search returns one page of Google: up to 10 organic results, plus ads, top_stories, knowledge_panel and related_keywords.
4. Page through the top 100 and save a CSV
$rows = [];
for ($page = 1; $page <= 10; $page++) {
$data = serpwiz('google/search', ['q' => 'best crm for startups', 'page' => $page]);
foreach ($data['results'] as $r) {
$rows[] = [count($rows) + 1, $r['title'], $r['url']];
}
if (empty($data['next_page'])) break;
}
$f = fopen('results.csv', 'w');
fputcsv($f, ['rank', 'title', 'url']);
foreach ($rows as $row) fputcsv($f, $row);
fclose($f);
echo 'Saved ', count($rows), ' results', PHP_EOL;
5. Google Maps places
The same function calls the Google Maps API, with up to 200 places per search:
$maps = serpwiz('google/maps', ['q' => 'dentists in Miami', 'num' => 20]);
foreach ($maps['results'] as $p) {
echo $p['title'], ' | ', $p['phone'] ?? '-', ' | ', $p['rating'] ?? '-', PHP_EOL;
}
What it costs
Each search is 1 query: $0.15 per 1,000 on monthly plans, $0.1125 with a year prepaid, and failed requests are free. Also available: the Python and Node.js versions of this guide.
More from the blog
This post as Markdown: /blog/google-search-api-php.md