我需要从Google自定义搜索API中获得尊重每个关键字的最流行的10个URL。我正在使用带有耗材库的PHP。将所有关键字发送到API时,我得到了所有结果。但是我面临着一个关键问题。
问题:如果我向API发送100个关键字,它将返回所有结果,但是当我看到API控制台时,我看到1000个查询正在发送100个关键字。
例如:
我正在发送250个关键字,并在控制台上显示1500个查询。
我的代码是:
<pre>
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
if(isset($_POST['submit'])) {
$script_start = microtime(true);
$results = array();
//Get all default CURL data for Search API.
$filename = 'keywords.txt'; // File name;
$api_key = !empty($_POST['api_key']) ? $_POST['api_key'] : '';
$engine_id = !empty($_POST['engine_id']) ? $_POST['engine_id'] : ''; //Demo Engine ID
$api_url = 'https://www.googleapis.com/customsearch/v1';
$number = !empty($_POST['number_of_result']) ? $_POST['number_of_result'] : 10; // How many results are showing.
$start = !empty($_POST['start']) ? $_POST['start'] : 0; // Start line from Text file.
$end = !empty($_POST['end']) ? $_POST['end'] : 5; // End line from Text file.
//get text file content line by line.
$all_search_keywords = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// echo '<pre>'; print_r($all_search_keywords); die;
if(!empty($all_search_keywords)){
//PHP pagination in array's like (0 - 10) no line.
$limited_keywords = array_slice( $all_search_keywords , $start , $end );
$client = new Client();
$requests = function () use($limited_keywords, $api_url, $api_key, $engine_id, $number) {
if (!empty($limited_keywords)) {
//echo '<pre>'; print_r($limited_keywords); die;
foreach ($limited_keywords as $search_keyword) {
$uri = $api_url . '?' . http_build_query([
'key' => $api_key,
'cx' => $engine_id,
'q' => $search_keyword,
'num' => $number,
]);
//echo '<pre>'; print_r($uri);
yield new Request('GET', $uri);
}
}
};
$pool = new Pool($client, $requests(), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) use (&$results) {
//echo "<span style='color: green; font-size: 18px;'> SUCCESS: $index</span><br>";
$result = json_decode($response->getBody()->getContents(), true);
$results[$index] = $result;
},
'rejected' => function ($reason, $index) use(&$results) {
// this is delivered each failed request
echo "<span style='color: red; font-size: 18px;'> ERROR: $index</span><br>";
//echo '<pre>'; print_r($reason); exit;
// if ($reason instanceof GuzzleHttp\Exception\ClientException) {
// $body = $reason->getResponse()->getBody();
// }
// echo $body.'<br>';
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
}
//echo '<pre>'; print_r($get_urls); die;
$time_elapsed_secs = microtime(true) - $script_start;
//echo "<br><br><span style='color: blue; font-size: 24px;'> ". round($time_elapsed_secs, 2) . "</span>";
// echo '<pre>';
// print_r($results); exit;
}
请建议我。