Repository navigation
Expand file tree
/
Copy pathserp.php
More file actions
74 lines (68 loc) · 2.34 KB
/
Copy pathserp.php
File metadata and controls
74 lines (68 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
// Fetch Google search results with the Semust SERP API (PHP 7.4+ with the curl extension).
//
// export SEMUST_API_USER=... SEMUST_API_PASSWORD=...
// php serp.php "best seo tools"
const API = "https://data.semust.com";
const WAIT = 60; // seconds the API holds the request open before answering 202
function request(string $method, string $url, ?array $payload = null): array
{
$ch = curl_init($url);
$headers = [];
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => WAIT + 30,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"SEMUST-API-USER: " . getenv("SEMUST_API_USER"),
"SEMUST-API-PASSWORD: " . getenv("SEMUST_API_PASSWORD"),
],
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) {
$parts = explode(":", $line, 2);
if (count($parts) === 2) {
$headers[strtolower(trim($parts[0]))] = trim($parts[1]);
}
return strlen($line);
},
]);
if ($payload !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
}
$body = curl_exec($ch);
if ($body === false) {
fwrite(STDERR, "Request failed: " . curl_error($ch) . "\n");
exit(1);
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [$status, $headers, $body];
}
// POST a request and return the final response, polling if the API answers 202.
function call(string $path, array $payload): array
{
[$status, $headers, $body] = request("POST", API . $path . "?wait=" . WAIT, $payload);
while ($status === 202) {
$task = json_decode($body, true);
sleep((int)($headers["retry-after"] ?? 5));
[$status, $headers, $body] = request("GET", $task["poll_url"]);
}
return [$status, $body];
}
$keyword = $argv[1] ?? "best seo tools";
[$status, $body] = call("/v1/serp", [
"keyword" => $keyword,
"language" => "en",
"country" => "US",
"format" => "json",
"start_page" => 1,
"end_page" => 1,
]);
if ($status !== 200) {
fwrite(STDERR, "Error {$status}: {$body}\n");
exit(1);
}
$data = json_decode($body, true);
foreach ($data["organic"] ?? [] as $r) {
printf("%2d. %s\n %s\n", $r["rank"], $r["title"], $r["link"]);
}