phpazure-cognitive-servicesbing-search

Bing Search API in PHP - missing webPages property in json response


I am trying to get search results as per the api documentation

Here is what I wrote in 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 [];
    }

I am getting response but it is not having webPages property. It has _type, rankingResponse, relatedSearches and videos properties only. I tested the same request in the api console. There I am getting the webPages property in the json response.

Any ideas what could have been the reason why I am not getting the webPages in PHP but works on microsoft's api tester site?


Solution

  • From the code snippet, you are passing the keyword to Bing web search API after encoding it.
    $url_encoded_keyword = urlencode('animation concepts and tutorials');

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

    Try without encoding the keyword. From their API testing console, HTTP request for the same keyword would appear as

    https://api.cognitive.microsoft.com/bing/v5.0/search?q=animation concepts and tutorials&count=10&offset=0&mkt=en-us&safesearch=Moderate