I have looked many questions similar to this one, but can't find the helpful answer.
As I know, it is not possible to receive more than 10 results from Google custom search API. However, I want to know how do I make multiple calls by increasing startIndex (start) parameter to show more result.
Below is my code to increase the start
parameter statically.
$json_string_1 = 'https://www.googleapis.com/customsearch/v1?key='.$api_key.'&cx='.$cx.'&q='.$q.'&start=1';
$jsondata_1 = file_get_contents($json_string_1);
$obj_1 = json_decode($jsondata_1, true);
print_r($obj_1);
$json_string_2 = 'https://www.googleapis.com/customsearch/v1?key='.$api_key.'&cx='.$cx.'&q='.$q.'&start=11';
$jsondata_2 = file_get_contents($json_string_2);
$obj_2 = json_decode($jsondata_2, true);
print_r($obj_2);
How do I call start
parameter dynamically as if I have n
number of startIndex
OR any way to call this API in a loop so startIndex
will auto-increment by 10.
I figured it out how to loop API with multiple calls by increasing start
and get the complete result at once.
$count = 200;
for($page=1; $page < $count; $page=$page+10) {
$json_string_1 = 'https://www.googleapis.com/customsearch/v1?key='.$api_key.'&cx='.$cx.'&q='.$q.'&start='.$page;
$jsondata_1 = file_get_contents($json_string_1);
$obj_1 = json_decode($jsondata_1, true);
foreach ($obj_1["items"] as $data) {
echo $data["title"]."<br>";
}
}
In the above code, get the $count
value from the query search results like,
$totalResults = $data["searchInformation"]["totalResults"];
$count = $totalResults/10; //per page number of counts are 10