How to use the Bing Search API in PHP

Posted by at 14 August, at 13 : 48 PM Print

Bing Logo

Microsoft has a Bing API that allows you to use the Bing search engine on your own website. API stands for Application Programming Interface for those that don’t know, and it’s a way to interact with the Bing service to integrate it with your PHP Web application. It’s pretty easy too.

First we need to understand how the Bing API works. Well, going over the Bing API documentation it appears there are several things going on before, during and after a search request to the Bing API through our Web application:

  • First, we make the request by a standard HTTP GET request. We specify the GET parameters (for example: index.php?parameter=value&another_parameter=another_value). The Bing API responds to the HTTP GET in a number of data formats, including:
    • JSON (JavaScript Object Notation)
    • XML
    • SOAP

    In this example however, we’ll concentrate on a JSON request. For more information about JSON, see this article on it or do a quick Google search.

  • Next, the Bing API responds to the request with a response using JSON. We then use a function to translate the JSON encoded data into PHP arrays for us to work with to display the results to the user.

It’s important to note in order to use the Bing API you need to register for an API key (free, of course) at the Bing Developer Centre. Once you’ve registered you’ll need to use this API key when sending requests to the Bing API through your Web application.

Once you’ve registered and got your API key we can start developing our Bing application immediately. So we’re going to send a request and request a response with the JSON protocol. The Using JSON page has in-depth information about sending requests and subsequent responses from the Bing API using the JSON protocol, so check it out first. Now in a request we’re using many different “classes” in the Bing API (and if you don’t know, the Bing API is object-oriented hence my referral to the word “class” – it simply means different features we can use in the Bing API is split into different sections, such as the SearchRequest class has functions (or “features”) that we use to make a request to the Bing API. The class we always use in a request is the SearchRequest class (as some of the “parameters” required in any type of request are part of the SearchRequest class), which has the following functions:

  • AppId – this is how we specify what our API ID is, in order to send a request to the Bing API.
  • Query – the actual URL encoded query we make, usually submitted through a form.
  • Source – what type of request we’re going to make (Bing refers this to SourceType – see the SourceType page for the list of all types of sources we can use – such as Web, Image and so forth).

(If you don’t understand what “classes” are, or object oriented programming, you could make a Google search after this article What is Object Oriented Programming in PHP to learn about object oriented programming in PHP.)

There are the only required functions we have to use as parameters in the GET request from the SearchRequest class. In actual fact, in order to make a request all we need is the Query, the Source and the AppId.
However there are optional “functions” we can use that specify how many results we want Bing to return to us, etc. That explained in a moment. Now if you make a Web SourceType request, bear in mind you will receive responses from many different classes, including:

  • SearchResponse.Version – which displays the version of the Bing API that is dealing with your response. This response is common to all types of SourceType responses.

(Remember, Search Response is a class – the Version bit is part of the SearchResponse class, separated by a period).

  • Query.SearchTerms – the search terms the user made; this response is common to all types of SourceType responses.

The following responses are specific to the Web SourceType responses:

  • WebResult.Url – the URL of the website in a search result
  • WebResult.CacheUrl – if Bing has a cache of the page, the URL to the cache copy will be in CacheUrl.
  • WebResult.DateTime – the last time this result was crawled by the Bing search bot.
  • WebResult.DeepLinks – if any other pages link to the search
    result’s URL, they will be part of this feature if you wish to display this information.
  • WebResult.Description – a description of the search result for you to display if you wish (recommended, of course).
  • WebResult.DisplayUrl – the same as the Url one above, but instead it’s formatted so you can display it without removing the http:// as it’s stripped already. This is the “green URL” you see below a search result.
  • WebResult.SearchTags – returns the search tags of this request, if you wish to display them, etc.
  • WebResult.Title – the title of the search result.

For a full list of responses you get from each time of SourceType request, see Working with SourceTypes page.

Ok, so we’ll get onto the code, here’s a working application – in the code the relevant parts are commented:

<body>
<?php
$search = trim($_POST['search']); // trim whitespace at start and end to ensure no empty query is submitted
if($_POST['submit']) {
if(strlen($search) == 0) {
echo "<p>Error: empty search</p>";
}
else {
$get = file_get_contents("http://api.bing.net/json.aspx?AppId=Your App ID here&Query=".urlencode($search)."&Sources=Web");
$decode = json_decode($get, TRUE); // TRUE for in array format
echo "<p><a href='index.php'>Home</a></p>";
echo "<p><i>1-15 of ".$decode['SearchResponse']['Web']['Total']." results</i></p>"; // total number of results found by Bing for the search query provided
$i = 0; // incremental variable for search result numbering
foreach($decode['SearchResponse']['Web']['Results'] as $res) { // foreach loop, to loop through each array value (result) as $res
$i++; // incrementation
echo "<p>".$i.": <a href='".$res['Url']."'>".$res['Title']."</a><br /><i>".$res['Description']."</i><br /><span style='font-size: 10pt;'>".$res['DisplayUrl']."</span></p>"; // display everything
}
}
}
?>
<div style='text-align: center'>
<h1>Search - powered by Bing</h1>
<form method="post" action="index.php">
<input type="text" name="search" size="50" />
<input type="submit" name="submit" value="Bing" />
</form>
</div>
</body>

By the way, just to let you know that $decode[‘SearchResponse’][‘Web’][‘Results’] contains the the url, Title, Description and DisplayUrl features, which we discussed earlier which is part of the WebResult class but the SourceType is called Web – hence such referral here.

To understand what’s what, why not make a basic application that returns the response from a query?

<body>
<?php
$search = trim($_POST['search']);
if($_POST['submit']) {
if(strlen($search) == 0) {
echo "<p>Error: empty search</p>";
}
else {
$get = file_get_contents("http://api.bing.net/json.aspx?AppId=Your App ID here&Query=".urlencode($search)."&Sources=Web&Web.Count=15");
$decode = json_decode($get, TRUE);
echo "<pre>";
print_r($decode); // let's print it in a more readable format
echo "</pre>";
}
}
?>
<div style='text-align: center'>
<h1>Search - powered by Bing</h1>
<form method="post" action="index.php">
<input type="text" name="search" size="50" />
<input type="submit" name="submit" value="Bing" />
</form>
</div>
</body>

Be Sociable, Share!

Ben Stones

Ben's main IT experience is on software, programming, website development and marketing topics including search engine optimisation. At eUKhost, he regularly works alongside the marketing department on product marketing strategies, and in the development and quality control of the communications which are sent to customers and through the press distribution network. Aside from his regular collaboration with the marketing department on product marketing objectives, Ben occasionally works with the design department in conjunction with the management team on the development of new product pages and the stringent quality control requirements.

Comments

comments

Industry News Tutorials Web Hosting

Related Posts

Post Your Comment

You must be logged in to post a comment.