Bing Search API无效

时间:2016-10-31 10:08:03

标签: php json api search bing-api

我想获取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;

?>

2 个答案:

答案 0 :(得分:1)

我强烈建议您切换到Microsoft Searchitive Services中提供的Bing Search API v5:Web Search API。您目前正在使用旧的Search API,该ID将在2016年12月的here中弃用。

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

这是一个示例php片段开始使用(注意:您需要先在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;
}

?>

答案 1 :(得分:0)

根据在UI中进行的选择,对图像/网络搜索进行代码更改。

    <?php
    include "bing_search.html";
    if ($_POST['query'])
    {
        if ($_POST['service_op'] == 'Image') {
            $URL = $rootUri = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search';
            // or insead of image search api use the responseFilter=Images with the search URL
        } else {
            $URL = $rootUri =     'https://api.cognitive.microsoft.com/bing/v5.0/search';
        }
        $keyword = $_POST['query'];
        //$URL = $URL.'?q='.$keyword.'&count=10&offset=0&mkt=en-us&safeSearch=Moderate';
        $URL = $URL.'?q='.$keyword.'&mkt=en-us&safeSearch=Moderate';
        if ($_POST['service_op'] != 'Image') {
            $URL .= "&responseFilter=News";
        }
        $ch = curl_init($URL);
        curl_setopt($ch, CURLOPT_HTTPGET, 1);

    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;