gpt4 book ai didi

php - 使用 PHP 输出谷歌搜索结果?

转载 作者:行者123 更新时间:2023-12-05 08:42:28 27 4
gpt4 key购买 nike

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

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

Notice: Undefined property: stdClass::$responseData in E:\XAMPP\htdocs\PHP Training\google.php on line 19

Notice: Trying to get property of non-object in E:\XAMPP\htdocs\PHP Training\google.php on line 19

这就是我目前所拥有的。下面的代码。

$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>"; }
}

API 工作正常,因为当我访问 This 时,它会吐出数组中的所有内容。示例: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"
}

最佳答案

你看过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);
}
}

关于php - 使用 PHP 输出谷歌搜索结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com