2016-09-13 70 views
1

的示例我試圖在沒有HTTP/Request2.php組件的情況下使用Bing的圖像搜索API獲取一些結果(as used in the official examples)。Bing圖像搜索API v5.0 PHP

據我所知,做出非常原始調用的唯一兩個必需參數是q這是查詢字符串和subscription key。必須使用標題發送key。環顧四周後,我發現這個非常簡單的例子來發送標頭的PHP:

$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats"; 
$aHTTP = array(
    'Ocp-Apim-Subscription-Key' => 'xxxxxxx', 
); 
$context = stream_context_create($aHTTP); 
$contents = file_get_contents($sURL, false, $context); 

echo $contents; 

但它不輸出任何東西。您是否願意幫助我使用Bing API的一個非常基本的示例?

回答

1

嘗試使用捲曲

$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats"; 
$key = "xxxxxxx"; 


$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $sURL); 
curl_setopt($ch, CURLOPT_TIMEOUT, '1'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key'); 
$content = curl_exec($ch); 

echo $content; 
+0

看起來'key'不被識別,因爲API會返回'Missing key'。 – Nicero

2

解決

由於瓦迪姆的提示我換頭髮送的方式,現在輸出的是JSON編碼的結果。 (請記住添加您的API訂閱密鑰。)

$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats"; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $sURL); 
curl_setopt($ch, CURLOPT_TIMEOUT, '1'); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: multipart/form-data', 
    'Ocp-Apim-Subscription-Key: xxxxx' 
)); 
$content = curl_exec($ch); 

echo $content; 

只是另一個提示。查詢過濾器和其他參數的語法將表單版本更改爲版本。例如,下面的正確5.0版本中的工作:

要爲貓的JPEG圖像只搜索,並得到30個結果使用方法:

q=cats&encodingFormat='jpeg'&count=30 

要只與大小200x200和500×500之間的「肖像」方面的圖片搜索使用方法:

q=cats&aspect=Tall&size=Medium 
0

這是我的工作代碼.. 替換********你的兵訂閱密鑰。

 $sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US"; 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $sURL); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: multipart/form-data', 
      'Ocp-Apim-Subscription-Key: *******************' 
     )); 
     $contents = curl_exec($ch); 
     $myContents = json_decode($contents); 
     if(count($myContents->value) > 0) { 
      foreach ($myContents->value as $imageContent) { 
       echo '<pre/>'; 
       print_r($imageContent); 
      } 
     }