Search code examples
phpgoogle-searchgoogle-search-api

How to use Google Search query in PHP?


I am trying to use Google Search query in my website, I need to get website URLs for the text I sent to the query, the code works fine for limited results, but then it stops working after some time, maybe Google disables it for some time?

Here is the code:

        $cleanQuery = str_replace(" ","+",$text);
        $url = 'http://www.google.com/search?q='.$cleanQuery;
        $scrape = file_get_contents($url);

$text is the text entered by the user while searching. But the problem is it works only for sometime, then it stops.

Working example: http://www.alleffort.com/tools/findurl.php

If you enter some text in the textarea, then on submits it should retrieve all the related information, but it is not working.


Solution

  • The problem is probably the string you are appending to the url:

     $cleanQuery = str_replace(" ","+",$text);
    

    This does not prepare the string correctly for use in a query string, you would need to encode more characters than just the space.

    Instead, you should use urlencode():

    $cleanQuery = urlencode($text);