-1

I wants to fetch the bing api results but not succeeded on that. Already used many codes and samples but didnt get my answer. Please is dere any mistake in my code or not.

There are two files 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>

Above is the html code below is php code

<?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;

?>
  • don't use print_r. use var_dump. especially on things that can be boolean true/false. Those will print_r as invisible/empty strings, var_dump will properly report them as `(bool)true` or whatever. – Marc B Nov 01 '16 at 14:22

2 Answers2

1

I strongly encourage you to switch to Bing Search API v5, which is available in Microsoft Cognitive Services: Web Search API. You are currently using the old Search API, which is going to be deprecated in Dec'2016 as mentioned here.

The new Bing Search APIs have far more features, fresh documentation and are actively supported by our engineering team. You can find sample code for popular programming languages at the bottom of the Search API's reference page.

Here's a sample php snippet to get started (note: you need to subscribe first for free at microsoft.com/cognitive to get a unique API subscription key)

<?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;
}

?>
0

Code changes for image / web search based on the selection made in 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;
Senthil
  • 2,156
  • 1
  • 14
  • 19