gpt4 book ai didi

php - Google API php 客户端 - 检索搜索结果详细信息

转载 作者:搜寻专家 更新时间:2023-10-31 21:25:53 25 4
gpt4 key购买 nike

我在使用 google 时遇到问题 https://github.com/google/google-api-php-client .我想要做的就是使用自定义搜索引擎 (CSE) 从搜索结果中获取一些详细信息。使用 bing API 同样的事情花了我 30 分钟,但我无法让它工作。 API 调用有效,我只是无法从返回的对象中获取结果。使用上面源代码中的示例,simple-query.php 使用 books API 工作正常(非常有用的示例!),我可以使用例如返回搜索结果的详细信息

    echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo $item['selfLink'],"<br /><br/> \n";
echo $item['etag'],"<br /> \n";
echo $item['volumeInfo']['title'],"<br /> \n";
echo $item['volumeInfo']['authors']['0'],"<br /> \n";
}

这是使用我的 API key 和 CSE ID。

但是,如果我尝试使用 CSE,我将无法使用返回的结果对象。所以修改简单的搜索示例:

<?php

include_once "templates/base.php";
echo pageHeader("Custom Image Search");

//API request
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Customsearch.php';

//Create the client
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Enter your API key
// Warn if the API key isn't changed.
if ($apiKey == '<YOUR_API_KEY>') {
echo missingApiKeyWarning();
}
$client->setDeveloperKey($apiKey);

$service = new Google_Service_Customsearch($client);

//Do the query
$query = 'donkey';
$optParams = array(
'imgSize' => 'large',
'searchType' => 'image',
'num' => '5',
'safe' => 'medium',
'cx' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx', //Added your cx or search engine ID here, see https://cse.google.com/cse/
);
$results = $service->cse->listCse($query, $optParams);



//Iterate over the results
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo "Test <br/>";
echo $item['link'], "<br /> \n";
}

这不会返回任何内容。

在 $results 上使用 var_dump 我可以看到它正在返回搜索结果(是的,我正在搜索驴的图像,作为示例!)。

但是使用书籍示例,我可以看到有 6 个结果:

echo "Results count: " .count($results);

但是用 cse 示例执行此操作返回 0。所以不出所料,我没有进行任何迭代。

那么,谁能告诉我如何使用 php 客户端和 CSE 实际获得结果?

谢谢

最佳答案

您应该使用 API 中包含的方法来检索结果和项目详细信息:

    foreach($results->getItems() as $k=>$item){
echo $item->getCacheId()."<br/>";
echo $item->getDisplayLink()."<br/>";
echo $item->getFileFormat()."<br/>";
echo $item->getFormattedUrl()."<br/>";
echo $item->getHtmlFormattedUrl()."<br/>";
echo $item->getHtmlTitle()."<br/>";
echo $item->getImage()."<br/>";
echo $item->getKind()."<br/>";
echo json_encode($item->getLabels())."<br/>";
echo $item->getLink()."<br/>";
echo $item->getMime()."<br/>";
echo json_encode($item->getPagemap())."<br/>";
echo $item->getSnippet()."<br/>";
echo $item->getTitle()."<br/>";
}

关于php - Google API php 客户端 - 检索搜索结果详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36281563/

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