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