Bing search API and Azure

2019-01-08 15:27发布

I am trying to programatically perform a search on Microsoft Bing search engine.

Here is my understanding:

  • There was a Bing Search API 2.0 , which will be replaced soon (1st Aug 2012)
  • The new API is known as Windows Azure Marketplace.
  • You use different URL for the two.

In the old API (Bing Search API 2.0), you specify a key (Application ID) in the URL, and such key will be used to authenticate the request. As long as you have the key as a parameter in the URL, you can obtain the results.

In the new API (Windows Azure Marketplace), you do NOT include the key (Account Key) in the URL. Instead, you put in a query URL, then the server will ask for your credentials. When using a browser, there will be a pop-up asking for a/c name and password. Instruction was to leave the account name blank and insert your key in the password field.

Okay, I have done all that and I can see a JSON-formatted results of my search on my browser page.

How do I do this programmatically in PHP? I tried searching for the documentation and sample code from Microsoft MSDN library, but I was either searching in the wrong place, or there are extremely limited resources in there.

Would anyone be able to tell me how do you do the "enter the key in the password field in the pop-up" part in PHP please?

Thanks alot in advance.

标签: php search bing
7条回答
我命由我不由天
2楼-- · 2019-01-08 15:45

Don't forget to put this:

base64_encode("ignored:".$accountKey)

instead of:

base64_encode($accountKey . ":" . $accountKey)
查看更多
冷血范
3楼-- · 2019-01-08 15:51

None of the above worked for me. Im running MAMP, this may be relevant. Try the below:


$accountKey = '=';


function sitesearch ($query, $site, $accountKey, $count=NULL){
  // code from http://go.microsoft.com/fwlink/?LinkID=248077

    $context = stream_context_create(array(
    'http' => array(
      'request_fulluri' => true,       
      'header'  => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
    ) 
    )); 

    $ServiceRootURL =  'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&';
    $WebSearchURL = $ServiceRootURL . '$format=json&Query=';  

    $request = $WebSearchURL . urlencode("'$query'"); // note the extra single quotes
    if ($count) $request .= "&\$top=$count"; // note the dollar sign before $top--it's not a variable!
    return json_decode(file_get_contents($request, 0, $context), true);
}


$q = "query";

if ($q){
  // get search results
  $articles = sitesearch ($q, $_SERVER['HTTP_HOST'], $accountKey , 100);

  foreach($articles['d']['results'] as $article) {
      echo " <p>".$article['Title'].'</p>';
      echo " <p>".$article['Description'].'</p>';
      echo " <p>".$article['Source'].'</p>';
      echo " <p>".strtotime($article['Date']).'</p>';
  }



}

FROM: http://bililite.com/blog/2012/06/05/new-bing-api/

查看更多
再贱就再见
4楼-- · 2019-01-08 15:51

Here is the example of how to call Bing/Azure API using Unirest library.

require_once '/path/to/unirest-php/lib/Unirest.php';

$accountKey = "xxx";
$searchResults = Unirest::get("https://api.datamarket.azure.com/Bing/Search/v1/Composite",
    array(),
    array(
        'Query' => '%27Microsoft%27',
        'Sources' => '%27web%2Bimage%2Bvideo%2Bnews%2Bspell%27',
        '$format' => 'json',
    ), $accountKey, $accountKey
);

// Results are here:
$objectArray = $searchResults->body->d->results;
$rawJson = $searchResults->raw_body;

You can omit Source parameter by defining it in the URL: https://api.datamarket.azure.com/Bing/Search/v1/Webor https://api.datamarket.azure.com/Bing/Search/v1/Image

Note: parameters in request URL are case-sensitive. For Bing they start with a capital letter.

查看更多
该账号已被封号
5楼-- · 2019-01-08 15:54

Here is a working example of the Search API just replace "XXXX" with your access key. Even I wasted quite a few hours trying to get it to work using cURL but it was failing because of "CURLOPT_SSL_VERIFYPEER" on local :( - so make sure your cURL opts are set properly.

$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, base64_encode("username:XXXX"));
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);

# Deliver
return $response;

# Have a great day!
curl_close($process);
查看更多
趁早两清
6楼-- · 2019-01-08 15:56

you can use bellow code to get bing search results

$acctKey = 'Your account key here';
$rootUri = 'https://api.datamarket.azure.com/Bing/Search';
$query = 'Kitchen';
$serviceOp ='Image';
$market ='en-us';
$query = urlencode("'$query'");
$market = urlencode("'$market'");
$requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query&Market=$market";
$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);
$response=json_decode($response);
echo "<pre>";
print_r($response);
echo "</pre>";
查看更多
We Are One
7楼-- · 2019-01-08 15:58

Documentation for new services can get a bit interesting - especially in the rabbit-warren of MSDN. The most clear explanation I can find is on the Migration Guide from this Bing Search API page. Best of all the migration guide has a nice simple example in PHP towards the end.

EDIT: Alright, the migration guide is a starting point, but it isn't the best example. Here are two methods that work for me (no proxy, firewalls etc. interfering):

Using file_get_contents

Note: 'allow_url_fopen' needs to be enabled for this to work. You can use ini_set (or change php.ini etc.) if it isn't.

if (isset($_POST['submit'])) 
{

    // Replace this value with your account key
    $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=';            
    $ServiceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';                    
    $WebSearchURL = $ServiceRootURL . 'Web?$format=json&Query=';

    $cred = sprintf('Authorization: Basic %s', 
      base64_encode($accountKey . ":" . $accountKey) );

    $context = stream_context_create(array(
        'http' => array(
            'header'  => $cred
        )
    ));

    $request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');

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

    $jsonobj = json_decode($response);

    echo('<ul ID="resultList">');

    foreach($jsonobj->d->results as $value)
    {                        
        echo('<li class="resultlistitem"><a href="' 
                . $value->URL . '">'.$value->Title.'</a>');
    }

    echo("</ul>");
}

Using cURL

If cURL is installed, which is normal these days:

<?php
  $query = $_POST['searchText'];

  $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
  $serviceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';  
  $webSearchURL = $serviceRootURL . 'Web?$format=json&Query=';

  $request = $webSearchURL . "%27" . urlencode( "$query" ) . "%27";

  $process = curl_init($request);
  curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($process, CURLOPT_USERPWD,  "$accountKey:$accountKey");
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  $response = curl_exec($process);
  $response = json_decode($response);

  echo "<ol>";
  foreach( $response->d->results as $result ) {
    $url = $result->Url;
    $title = $result->Title;

    echo "<li><a href='$url'>$title</a></li>";
  }
  echo "</ol>";
?>

[WTS] changed SearchWeb to Search.

查看更多
登录 后发表回答