1

我正在尝试根据api 文档获取搜索结果

这是我用 PHP 写的

    require_once 'HTTP/Request2.php';

    $api_key = 'my_bing_search_api_key';
    $url_encoded_keyword = urlencode('animation concepts and tutorials');


    $request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/search');      
    $headers = [
        'Ocp-Apim-Subscription-Key' => $api_key
    ];        
    $request->setHeader($headers);

    $url = $request->getUrl();

    $parameters = [
        'q' => $url_encoded_keyword,
        'count' => '10',
        'offset' => '0',
        'safesearch' => 'Strict',
    );

    $url->setQueryVariables($parameters);

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

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

    $search_result = null;
    try {
        $response = $request->send();
        $search_results = json_decode($response->getBody(), true);
        return $search_results;
    } catch (HttpException $ex) {            
        return [];
    }

我收到了回复,但它没有 webPages 属性。它只有 _type、rankingResponse、relatedSearches 和视频属性。我在api 控制台中测试了相同的请求。我在 json 响应中获得了 webPages 属性。

任何想法可能是我没有在 PHP 中获取 webPages 而是在微软的 api 测试器站点上工作的原因?

4

1 回答 1

1

从代码片段中,您将在编码后将关键字传递给 Bing Web 搜索 API。
$url_encoded_keyword = urlencode('动画概念和教程');

$parameters = [
    'q' => $url_encoded_keyword,
    'count' => '10',
    'offset' => '0',
    'safesearch' => 'Strict',
);

尝试不编码关键字。在他们的API 测试控制台中,相同关键字的 HTTP 请求将显示为

https://api.cognitive.microsoft.com/bing/v5.0/search?q= 动画概念和教程&count=10&offset=0&mkt=en-us&safesearch=Moderate

于 2017-04-06T11:51:57.343 回答