Bogdan
Bogdan

Reputation: 1083

How to fetch number of results from a Google query

Whilst trying to develop a keyword difficulty tool of my own ran into a problem when fetching the total number of results from a Google query. To make it as clear as possible here's a screen of the number I'm looking to fetch: enter image description here

I could't find any references of how to do this on the Google Custom Search API so I've built a small scraper, but I feel it's not the best method of doing it. Here's my code:

<?php
$url = "http://www.google.com/search?q=".$keyword;
$text = file_get_contents($url);
//get string between 2 strings function
function get_string_between($string, $start, $end){
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);
}
//fetch the string between "About" and "results"
$res = get_string_between($text, "About", "results");
//keep only numeric characters
$res = preg_replace('/[^0-9]+/', '', $res);
?>

Can you suggest a better way of doing this? (Preferably using a Google API)

Upvotes: 4

Views: 2704

Answers (1)

deizel.
deizel.

Reputation: 11202

Use a regular expression:

$params = array('q' => 'shark with lasers that shoot monkeys with balloons on skyscrapers please give me less results asdafasddfg');
$content = file_get_contents('http://www.google.com/search?' . http_build_query($params));
preg_match('/About (.*) results/i', $content, $matches);
echo !empty($matches[1]) ? $matches[1] : 0;
// output: 14,300

I can't find anything in their APIs. Beware, this is against Google TOS. Bing's API will give you a result count.

Upvotes: 1

Related Questions