【问题标题】:Bing Search API is not working必应搜索 API 不工作
【发布时间】:2016-10-31 10:08:03
【问题描述】:

我想获取 bing api 结果,但没有成功。已经使用了许多代码和示例,但没有得到我的答案。请问我的代码是否有任何错误。

有两个文件 1. bing.php (HTML) 2. bing_code.php (PHP)

<html>
<head>
<title>Bing Search Tester (Basic)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Bing Search Tester (Basic)</h1>
<form method="POST" action="bing_code.php">
<label for="service_op">Service Operation</label><br/>
<input name="service_op" type="radio" value="Web" CHECKED /> Web
<input name="service_op" type="radio" value="Image" /> Image <br/>
<label for="query">Query</label><br/>
<input name="query" type="text" size="60" maxlength="60" value="" /><br /><br />
<input name="bt_search" type="submit" value="Search" />
</form> <h2>Results</h2>

</body>
</html>

上面是html代码 下面是php代码

<?php

$acctKey = 'key';

$rootUri = 'https://api.datamarket.azure.com/Bing/Search';

$contents = file_get_contents('bing.php');

if ($_POST['query'])
{

$query = urlencode("'{$_POST['query']}'");

$serviceOp = $_POST['service_op'];

$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query";

$auth = base64_encode("$acctKey:$acctKey");

$data = array('http' => array('request_fulluri' => true,'ignore_errors' => true,'header' => "Authorization: Basic $auth"));

$context = stream_context_create($data);

$response = file_get_contents($requestUri, 0, $context);

$jsonObj = json_decode($response, true);

print_r($jsonObj); echo "nothing!"; die();

$resultStr = '';
if( ( is_array( $jsonObj->d->results )) && ( ! empty( $jsonObj->d->results ) ) ) {
    foreach($jsonObj->d->results as $value)
    {
        switch ($value->__metadata->type)
        {
            case 'WebResult':
            $resultStr .= "<a href=\"$value->Url\">{$value->Title}</a><p>{$value->Description}</p>";
            break;
            case 'ImageResult': $resultStr .= "<h4>{$value->Title} ({$value->Width}x{$value->Height}) " . "{$value->FileSize} bytes)</h4>" . "<a href=\"{$value->MediaUrl}\">" . "<img src=\"{$value->Thumbnail->MediaUrl}\"></a><br />";
            break;
        }
    }
} else {
    if( ! is_array( $jsonObj->d->results )) {

        echo "jsonObj->d->results is not an array!";

    } elseif( empty( $jsonObj->d->results )) {

        echo "jsonObj->d->results is empty!";

    }
}

$contents = str_replace('{RESULTS}', $resultStr, $contents);

}

echo $contents;

?>

【问题讨论】:

  • 不要使用 print_r。使用 var_dump。特别是在可以是布尔真/假的事情上。这些将 print_r 作为不可见/空字符串,var_dump 将正确报告它们为(bool)true 或其他。

标签: php json api search bing-api


【解决方案1】:

我强烈建议您切换到 Microsoft 认知服务中提供的 Bing Search API v5:Web Search API。您目前使用的是旧版 Search API,如 here 所述,该 API 将于 2016 年 12 月弃用。

新的必应搜索 API 具有更多功能、全新文档,并得到我们工程团队的积极支持。您可以在Search API's reference page 底部找到流行编程语言的示例代码。

这是一个示例 php sn-p 开始使用(注意:您需要先在microsoft.com/cognitive免费订阅以获得唯一的 API 订阅密钥)

<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Ocp-Apim-Subscription-Key' => '{subscription key}',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
    'q' => 'bill gates',
    'count' => '10',
    'offset' => '0',
    'mkt' => 'en-us',
    'safesearch' => 'Moderate',
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_GET);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();  //toDo: Parse the response object to get the web, image, video etc. results.  
    echo $response->getBody();
}
catch (HttpException $ex)
{
    echo $ex;
}

?>

【讨论】:

    【解决方案2】:

    根据 UI 中的选择更改图像/网络搜索的代码。

    curl_setopt($ch,CURLOPT_HTTPHEADER,array('Ocp-Apim-Subscription-Key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX','Content-Type: application/json')); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($ch); echo "<pre>"; $jsonObj = $response = json_decode($response); //print_r($jsonObj); // die(); $resultStr = ''; if(isset($jsonObj->value) && ( is_array( $jsonObj->value ))) { foreach($jsonObj->value as $value) { echo "<a target='_blank' href='".$value->contentUrl."'><img src='".$value->thumbnailUrl."'></a><p>{$value->name}</p>"; } } else if ( isset($jsonObj->news ) && ( ! empty( $jsonObj->news->value ) ) ) { foreach($jsonObj->news->value as $value) { echo "<a target='_blank' href='".$value->url."'><p>"; echo "{$value->name}</p></a>"; if (isset($value->image->thumbnail->contentUrl)) { echo "<img src='".$value->image->thumbnail->contentUrl."'>"; } echo "<p>{$value->description}</p>"; } } else { echo "No results found"; } } ?&gt;

    【讨论】: