使用 PHP 输出 Google 搜索结果?

squ*_*idg 2 php search

我查看了有关 stackoverflow 的几个旧答案,但它们都已过时,并且它们使用的 API 不再可用。

我已经创建了一个 JSON/Atom API、CX 密钥并使用了一个脚本 感谢 Adam Fischer 我在这里找到了但是当我尝试时我现在能够在页面上输出打印结果我得到了错误:

注意:未定义的属性:第 19 行 E:\XAMPP\htdocs\PHP Training\google.php 中的 stdClass::$responseData

注意:第 19 行尝试在 E:\XAMPP\htdocs\PHP Training\google.php 中获取非对象的属性

这是我到目前为止。下面的代码。

$url = 'https://www.googleapis.com/customsearch/v1?key=[MY API KEY]&cx=[MY CX KEY]&q=lecture';

$body = file_get_contents($url);
$json = json_decode($body);

for($x=0;$x<countif ($json->responseData->results);$x++>items){

echo "<b>Result ".($x+1)."</b>";
echo "<br>URL: ";
echoforeach ($json->responseData->results[$x]->url;
echo>items "<br>VisibleURL:as ";$item){
echo $json->responseData->results[$x]->visibleUrl;
echo "<br>Title: ";
echo $json->responseData->results[$x]->title;
echo "<br>Content: ";print_r($item)
echo $json->responseData->results[$x]->content;
echo "<br><br>"; }
}
Run Code Online (Sandbox Code Playgroud)

API 工作正常,因为当我访问它时会吐出数组中的所有内容。示例:dl.dropboxusercontent.com/u/47731225/sample.txt

我正在尝试使 $url 我看到的结果例如像 Google 搜索一样显示在我的页面上,例如:prntscr.com/drum5u

{
   "kind": "customsearch#result",
   "title": "The Tank, Haydon Allen Lecture Theatre, Building 23, ANU",
   "htmlTitle": "The Tank, Haydon Allen \u003cb\u003eLecture\u003c/b\u003e Theatre, Building 23, ANU",
   "link": "https://www.google.com/mymaps/viewer?mid=1YGFZHcZ20jPvy5OiaKT1voy841Q&hl=en",
   "displayLink": "www.google.com",
   "snippet": "\"The Tank\", Haydon Allen Lecture Theatre, Building 23, The Australian National \nUniversity (ANU), Canberra, Australia.",
   "htmlSnippet": "&quot;The Tank&quot;, Haydon Allen \u003cb\u003eLecture\u003c/b\u003e Theatre, Building 23, The Australian National \u003cbr\u003e\nUniversity (ANU), Canberra, Australia.",
   "cacheId": "hTeucZ5TewoJ",
   "formattedUrl": "https://www.google.com/mymaps/viewer?mid...hl=en",
   "htmlFormattedUrl": "https://www.google.com/mymaps/viewer?mid...hl=en",
   "pagemap": {
    "cse_thumbnail": [
     {
      "width": "221",
      "height": "228",
      "src": "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSntx5YhQgJQeJ6RAZajOx7SGOwh0oUu8jtpY6VOAS75V_oNkiXx923ro4"
     }
Run Code Online (Sandbox Code Playgroud)

Ada*_*her 5

您是否查看了从 API 返回的 json?我的猜测是,它与您期望的完全不同

https://developers.google.com/custom-search/json-api/v1/reference/cse/list

澄清后,您的结果与您的代码预期的完全不同。

正确的代码应该是这样的

$url = 'https://www.googleapis.com/customsearch/v1?key=[MY API KEY]&cx=[MY CX KEY]&q=lecture';

$body = file_get_contents($url);
$json = json_decode($body);
if ($json->items){
   foreach ($json->items as $item){
      print_r($item);
   }
}
Run Code Online (Sandbox Code Playgroud)