Jan
Jan

Reputation: 663

CSE Google Custom Page api show 50 results PHP?

I'm trying to get the first 50 results of the Google CSE API with the following PHP code.

The problem is that it combines the two pages sow the results are getting messed up like the first position is the one of the first page and the second position is the second of the second page and so on. Can someone tell me what I am doing wrong here?

What I actually want to do is get the first 50 results in a array, but the code below gives me mixed results.

$apiKey = "theapikey";

$query = "news";

for ($i = 1; $i <= 5; $i++) {

$ch = curl_init();

 $request = "https://www.googleapis.com/customsearch/v1?q=" . urlencode( "$query" ) . "&cx=013594553343653397533:q-qkkaltmay" ."&key=" . $apiKey . "&start=" . $i;

curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$output = curl_exec($ch);
$output = json_decode($output);

foreach( $output->items as $result ) {

    $url = $result->link;

    ${"items" . $i}[] = $url;

  } 

}

  echo json_encode($items1);

Upvotes: 0

Views: 1024

Answers (1)

David Huyck
David Huyck

Reputation: 41

It looks like you are adding each set of 10 results into a separate array, so $items1 has the first 10 results, $items2 has the next 10, etc. If you want all 50 results in a single array, there is no need to use an index in the array's name.

Also, the "start" parameter is the number of the result you want, not the number of the result set - so you want the first query to start at 1, the second to start at 11, the third at 21, etc.

You may also want to check that there is something in the result before adding it to your array.

I might do something more like so:

$apiKey = "theapikey";
$query = "news";
$items = array();

for ($i = 1; $i <= 5; $i++) {

  $ch = curl_init();

  $request = "https://www.googleapis.com/customsearch/v1?" .
    "q=" . urlencode( "$query" ) . 
    "&cx=013594553343653397533:q-qkkaltmay" .
    "&key=" . $apiKey .
    "&start=" . ( ($i - 1)*10 + 1 );

  curl_setopt($ch, CURLOPT_URL, $request);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

  $output = curl_exec($ch);
  $output = json_decode($output);

  foreach( $output->items as $result ) {

    if ($url = $result->link && trim($url)) $items[] = $url;

  } 

}

echo json_encode($items);

Finally, a couple caveats:

  • There is an existing question about whether this JSON api is deprecated and possibly going away.
  • Each query for the next 10 results counts against your quota. If you are worried about running out of queries each month, or if you are paying for quota increases, you may want to consider only retrieving what you need.

Upvotes: 2

Related Questions