Snabbstart: Använda PHP för att anropa API för webbsökning i Bing
Varning
Den 30 oktober 2020 flyttade Bing-sökning API:er från Azure AI-tjänster till Bing-sökning Services. Den här dokumentationen tillhandahålls endast som referens. Uppdaterad dokumentation finns i dokumentationen för API:et för Bing-sökning. Anvisningar om hur du skapar nya Azure-resurser för Bing-sökning finns i Skapa en Bing-sökning resurs via Azure Marketplace.
Använd den här snabbstarten för att göra ditt första anrop till API:et för webbsökning i Bing. Det här Node.js-programmet skickar en sökbegäran till API:et och visar JSON-svaret. Även om det här programmet är skrivet i JavaScript är API:et en RESTful-webbtjänst som är kompatibel med de flesta programmeringsspråk.
Förutsättningar
Här följer några saker som du behöver innan du kör den här snabbstarten:
- PHP 5.6.x eller senare
- En prenumerationsnyckel
Skapa en Azure-resurs
Börja använda API:et för webbsökning i Bing genom att skapa någon av följande Azure-resurser:
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd den kostnadsfria prisnivån för att prova tjänsten och uppgradera senare till en betald nivå för produktion.
- Tillgänglig via Azure Portal tills du tar bort resursen.
- Använd samma nyckel och slutpunkt för dina program i flera Azure AI-tjänster.
Aktivera stöd för säkert HTTP
Innan vi börjar letar du upp php.ini och avkommentarer den här raden:
; extension=php_openssl.dll
Skapa ett projekt och definiera variabler
Skapa ett nytt PHP-projekt i valfri IDE eller redigeringsprogram. Lägg till inledande och avslutande taggar:
<?php
och?>
.För värdet
$endpoint
kan du använda den globala slutpunkten i följande kod eller använda den anpassade underdomänslutpunkten som visas i Azure Portal för resursen.Bekräfta att
$endpoint
värdet är korrekt och ersätt$accesskey
värdet med en giltig prenumerationsnyckel från ditt Azure-konto.Du kan också anpassa sökfrågan genom att ersätta värdet för
$term
.
$accessKey = 'enter key here';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
$term = 'Microsoft Cognitive Services';
Skapa en begäran
Den här koden deklarerar en funktion med namnet BingWebSearch
som används för att konstruera begäranden till API:et för webbsökning i Bing. Den tar tre argument: $url
, $key
och $query
.
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);
// 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);
}
Göra en begäran och skriva ut svaret
Den här koden verifierar prenumerationsnyckeln, gör en begäran och skriver ut svaret.
// 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_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");
}
Färdigställa allt
Det sista steget är att verifiera koden och köra den. Om du vill jämföra din kod med vår finns det fullständiga programmet här:
<?php
$accessKey = 'enter key here';
$endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/search';
$term = 'Microsoft Cognitive Services';
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), 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");
}
?>
Exempel på JSON-svar
Svar från API för webbsökning i Bing returneras som JSON. Det här exempelsvaret har trunkerats för att visa ett enskilt resultat.
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "Microsoft Cognitive Services"
},
"webPages": {
"webSearchUrl": "https://www.bing.com/search?q=Microsoft+cognitive+services",
"totalEstimatedMatches": 22300000,
"value": [
{
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0",
"name": "Microsoft Cognitive Services",
"url": "https://www.microsoft.com/cognitive-services",
"displayUrl": "https://www.microsoft.com/cognitive-services",
"snippet": "Knock down barriers between you and your ideas. Enable natural and contextual interaction with tools that augment users' experiences via the power of machine-based AI. Plug them in and bring your ideas to life.",
"deepLinks": [
{
"name": "Face",
"url": "https://azure.microsoft.com/services/cognitive-services/face/",
"snippet": "Add facial recognition to your applications to detect, identify, and verify faces using the Face service from Microsoft Azure. ... Cognitive Services; Face service;"
},
{
"name": "Text Analytics",
"url": "https://azure.microsoft.com/services/cognitive-services/text-analytics/",
"snippet": "Cognitive Services; Text Analytics API; Text Analytics API . Detect sentiment, ... you agree that Microsoft may store it and use it to improve Microsoft services, ..."
},
{
"name": "Computer Vision API",
"url": "https://azure.microsoft.com/products/ai-services?activetab=pivot:visiontab",
"snippet": "Extract the data you need from images using optical character recognition and image analytics with Computer Vision APIs from Microsoft Azure."
},
{
"name": "Emotion",
"url": "https://www.microsoft.com/cognitive-services/en-us/emotion-api",
"snippet": "Cognitive Services Emotion API - microsoft.com"
},
{
"name": "Bing Speech API",
"url": "https://azure.microsoft.com/services/cognitive-services/speech/",
"snippet": "Add speech recognition to your applications, including text to speech, with a speech API from Microsoft Azure. ... Cognitive Services; Bing Speech API;"
},
{
"name": "Get Started for Free",
"url": "https://azure.microsoft.com/services/cognitive-services/",
"snippet": "Add vision, speech, language, and knowledge capabilities to your applications using intelligence APIs and SDKs from Cognitive Services."
}
]
}
]
},
"relatedSearches": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches",
"value": [
{
"text": "microsoft bot framework",
"displayText": "microsoft bot framework",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+bot+framework"
},
{
"text": "microsoft cognitive services youtube",
"displayText": "microsoft cognitive services youtube",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+youtube"
},
{
"text": "microsoft cognitive services search api",
"displayText": "microsoft cognitive services search api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+search+api"
},
{
"text": "microsoft cognitive services news",
"displayText": "microsoft cognitive services news",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+news"
},
{
"text": "ms cognitive service",
"displayText": "ms cognitive service",
"webSearchUrl": "https://www.bing.com/search?q=ms+cognitive+service"
},
{
"text": "microsoft cognitive services text analytics",
"displayText": "microsoft cognitive services text analytics",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+text+analytics"
},
{
"text": "microsoft cognitive services toolkit",
"displayText": "microsoft cognitive services toolkit",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+toolkit"
},
{
"text": "microsoft cognitive services api",
"displayText": "microsoft cognitive services api",
"webSearchUrl": "https://www.bing.com/search?q=microsoft+cognitive+services+api"
}
]
},
"rankingResponse": {
"mainline": {
"items": [
{
"answerType": "WebPages",
"resultIndex": 0,
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0"
}
}
]
},
"sidebar": {
"items": [
{
"answerType": "RelatedSearches",
"value": {
"id": "https://api.cognitive.microsoft.com/api/v7/#RelatedSearches"
}
}
]
}
}
}