如何从Bing搜索API响应中包含相关搜索?
我正在尝试根据此处的文档来将responseFilter的值设置为RelatedSearches:https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-web-api-v7-reference#relatedsearchanswer
以下是我的代码,该代码基于来自Bing的示例。我已将“&responseFilter = RelatedSearches”添加到由file_get_contents()获取的URL中。
我回来的错误是:
PHP Warning: file_get_contents(https://api.cognitive.microsoft.com/bing/v7.0/search?responseFilter=RelatedSearches&q=iphone+case): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
很明显,我将其错误地应用了。要使其正常运行,我可以更改什么?
<?php
$accessKey = 'abc123';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
$term = 'burrito recipe';
function BingWebSearch ($url, $key, $query) {
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&responseFilter=RelatedSearches", false, $context);
$headers = array();
foreach ($http_response_header as $k => $v) {
$h = explode(":", $v, 2);
if (isset($h[1]))
if (preg_match("/^BingAPIs-/", $h[0]) || preg_match("/^X-MSEdge-/", $h[0]))
$headers[trim($h[0])] = trim($h[1]);
}
return array($headers, $result);
}
if (strlen($accessKey) == 32) {
print "Searching the Web for: " . $term . "\n";
list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
print "\nJSON Response:\n\n";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
} else {
print("Invalid Bing Search API subscription key!\n");
print("Please paste yours into the source code.\n");
}
?>
答案 0 :(得分:0)
“ 403 Forbidden”是提示。您无权请求RelatedSearches,除非您按照以下说明位于S1实例上:https://azure.microsoft.com/en-us/pricing/details/cognitive-services/search-api/