谷歌API php客户端-检索搜索结果的详细信息


Google API php client - retrieve search result details

我在谷歌上遇到问题https://github.com/google/google-api-php-client.我想做的就是使用自定义搜索引擎(CSE)从搜索结果中获取一些细节。同样的事情花了我30分钟使用bing API,但我无法让它工作。API调用正在工作,我只是无法从返回的对象中获得结果。使用上面来源的示例,simple-query.php使用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密钥和CSE ID。

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

<?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/>";
    }

好吧,这就是我最后的做法,只是把它做成一个数组,然后使用array_walk_recurative:

//Making the returned object into an array
$array =  (array) $results;
function array_print($item, $key)
{
     if($key=='link'){
       echo $item ."<br>";
     }
}
array_walk_recursive($array, 'array_print');