Я пытался следовать официальному руководству Quickstart: Use PHP to call the Bing Web Search API
, чтобы скопировать код и запустить с моим ключом. Он не сработал, как ваш, и получил результат, как показано на рисунке ниже.
Затем мне стало известно о вашей проблеме, которая может быть такой же, как и у другого потока SO. Переводчик Microsoft Azure возвращает значение null с PHP API .
В Azure существует два типа API Cognitive Service для Bing Web Search, включая All Cognitive Services
(подписка All-in-one) и Bing Search v7
(только поиск Bing), как показано на рисунках ниже.
Рис. 1. Тип API All Cognitive Services
(подписка All-in-one), конечная точка которого зависит от региона обслуживания (Location
)
Рис. 2. Тип API Bing Search v7
(только поиск Bing)
Они используют разные конечные точки, например, в моем All Cognitive Service
из Location Southeast Asia
, конечная точка - https://southeastasia.api.cognitive.microsoft.com/
. А для Bing Search v7 в этом типе API конечная точка должна быть изменена на https://southeastasia.api.cognitive.microsoft.com/bing/v7.0/search
.
Так что официальный код для PHP нужно просто изменить двумя строками кода, как показано ниже, после того, как я проверил успех.
Для использования типа API All Cognitive Services
, код:
$accessKey = '<your key for API type of All Cognitive Services>';
$endpoint ='https://<the region of your cognitive service like southeastasia>.api.cognitive.microsoft.com/bing/v7.0/search';
Для использования типа API Bing Search v7
, код:
$accessKey = '<your key for API type of Bing Search v7>';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
Для вашего второго вопроса в вашем комментарии, простое решение для веб-страницы HTML и сценария php приведено ниже.
searchbar.html
<!DOCTYPE html>
<html>
<body>
<form name="bing" method="POST" action="search.php">
<input type="text" name="term">
<input type="submit" value="Search">
</form>
</body>
</html>
search.php : просто нужно изменить официальный код для $term
.
<?php
// as above
$accessKey = '<the key of your Cognitive Services>';
$endpoint = '<the endpoint of your Cognitive Services>';
// The `term` index is mapping to the `name` value of type `text` of tag `input` name `term`.
// Case when use `method="POST"` in form tag, the value of `term` got by `$_POST` method
// Or case when use `GET` method, it change to `$_GET`.
$term = $_POST['term'];
function BingWebSearch ($url, $key, $query) {
/* Prepare the HTTP request.
* NOTE: Use the key 'http' even if you are making an HTTPS request.
* See: http://php.net/manual/en/function.stream-context-create.php.
*/
$headers = "Ocp-Apim-Subscription-Key: $key\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
// Perform the request and get a JSON response.
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query), false, $context);
echo $result;
// Extract Bing HTTP headers.
$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);
}
// Validates the subscription key.
if (strlen($accessKey) == 32) {
print "Searching the Web for: " . $term . "\n";
// Makes the request.
list($headers, $json) = BingWebSearch($endpoint, $accessKey, $term);
print "\nRelevant Headers:\n\n";
foreach ($headers as $k => $v) {
print $k . ": " . $v . "\n";
}
// Prints JSON encoded response.
print "\nJSON Response:\n\n";
echo $json;
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");
}
?>