0
我想从PHP进行一个程序化的Google搜索,并没有用。我得到了我之后的JSON对象,但它的[totalResults] => 0,适用于我搜索的所有内容。我使用的apiKey是服务器密钥,customSearchEngineKey是我通过here指令创建的自定义搜索引擎。我知道这是有效的,因为我尝试过使用其他语言,但不能使用其他语言作为最终的程序(我不想说为什么),但是当我将它带到PHP中时,它由于某种原因失败。为什么??PHP谷歌搜索不返回任何东西
这是我的PHP代码,顺便说一句:
<?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
}
?>
是否有人会帮助我或这个,或以其他方式发送一些建议我的方式? – 2014-10-29 21:55:00