Search code examples
phpgoogle-custom-search

PHP Google Search not returning anything


I am trying to conduct a programmatic Google Search from PHP, and with no avail. I get the JSON object that I am after, but it has [totalResults] => 0, for everything that I have searched for. The apiKey that I am using is a server key, and the customSearchEngineKey is for a Custom Search Engine that I have created via the instructions here. I know this works, because I have tried in otherLanguage, but cannot use otherLanguage for the final program (I would rather not say why), but when I bring it over to PHP, it, for some reason, fails. Why??

This is my PHP code, by the way:

<?php
    // turn on the use of session variables, if it has not already been done
    session_start();
    // declare function that creates the URL for the Google search associated with a query
    function makeSearchString($query, $startNumber = 1, $count = 10)
    {
        // declare $apiKey,$customSearchEngineKey
        $apiKey = "AIzaSyCW6jCkVPGWRd2PN1ZHeOKq8haJqkYqEwQ";
        $customSearchEngineKey = "003207291839125798740:4fbhl2kr0mi";
        // set up searchString with $apiKey,$customSearchEngineKey
        $searchString = "https://www.googleapis.com/customsearch/v1?key=" . $apiKey . "&cx=" . $customSearchEngineKey . "&q=";
        // split query into an array with ' ' as the delimiter (regex is "/[ ]+/")
        $theQueries = explode("/[ ]+/", $searchString);
        // for each subquery in theQueries
        foreach ($theQueries as $subquery)
            // append subquery to searchString
            $searchString .= $subquery;
        // specify that the response should be in JSON, in searchString
        $searchString .= "&alt=json";
        // try to turn safeSearch on
        $searchString .= "&safe=high";
        // if startNumber is not 1 
        if ($startNumber != 1)
            // specify startNumber, in searchString
            $searchString .= ("&start=" . $startNumber);
        // if count is not 10 
        if ($count != 10)
            // specify count, in searchString
            $searchString .= ("&num=" . $count);
        // return searchString
        return $searchString;
    }

    /* Don't forget that you need to test this function. Try it with at least 2 searches... */
    // declare function that returns the JSON associated with a Google search tied to query
    function getJSONStringFor($query)
    {   
        // if $query is a URL that contains the first few characters in the defaultSearchString
        if (strpos($query, "https://www.googleapis.com/customsearch/v1?key=") !== false)
        {
            // return the file contents for that $query
            return file_get_contents($query);
        }       
        // makeSearchString for $query and get the JSONString from that searchString
        return file_get_contents(makeSearchString($query));
    }

    // if the searchData in $_SESSION is not already initialized
    if (!isset($_SESSION['searchData']))
        // initialize it
        $_SESSION['searchData'] = array();
    // get the terms to search for /* where from, I don't know!! They should at least be an array of Strings */
    /* For now, we can simply create an array of three terms to search for */
    $terms = array("alopecia", "Superman", "Spiderman");
    // for each term
    foreach ($terms as $term)
    {
        // get the JSONString
        // parse the JSONString into an associative array
        $array = json_decode(getJSONStringFor($term), true);
        print_r($array);    /* returns no results for some reason */
        // for each searchResult in that array 

            // if there is pagemap and it has a cse_image 
                // add it as a searchResult for that queryResult
        // append queryResult to searchData
    }
?>

Solution

  • I figured it out. The problem was with my makeSearchString(), namely with this line:

    $theQueries = explode("/[ ]+/", $searchString);

    I was accidentally telling the PHP compiler to split the $searchString into an array, when I was trying to split $query into an an array. So, I changed it to $theQueries = explode("/[ ]+/", $query); and all went well!