Postcards From My Life

Lint I find in my mind's belly-button.
  • EPK
  • Consulting
  • Resume
  • Nerd Herding
  • Talks
  • How to Plan a Website
  • Zend Framework
« Seeing Microsoft in the big picture
Flash Builder 4 and packaging »

Bing Search API wrapper for PHP

Dear Reader,

Back in March I had the opportunity to work on a project for Microsoft that is now coming to light. I was tasked with writing a PHP wrapper for the Bing API that Microsoft has been building. I’ve written API wrappers before and it is either a fun experience or it is a nightmare, depending on whether the API is easy to work with. I am pleased to report that the Bing Search API is well thought out and very easy to work with. For PHP developers, I am hoping that what I am about to show you makes it even easier.

QuickStart

Ok, if you don’t care for the rambling, here is everything you need to get going.

  • The Code
  • Get an API Key
  • The API Docs You will need an MSDN login to access the docs.

The steps are easy.

  • Grab the code and put it somewhere in your include path.
  • Get an application key. (They are free)
  • Write you a quick index.php that looks something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<html>
    <head>
        <title> Cal's Bing Search QuickTest</title>
    <body>
<?PHP
function __autoload($className)
{
    $fileName = strtr($className,'_',DIRECTORY_SEPARATOR).".php";
    include $fileName;
    return;
}
 
$apiKey = '';
 
$o = new Msft_Bing_Search($apiKey);
$o->setQuery('zend framework')
  ->setWebCount(10)
  ->setSite('calevans.com')
  ->setSource('Web')
  ->setSource('Image')
  ->setAdult('Off')
;
 
$raw = $o->search();
echo "<h2>Raw</h2>";
echo "<textarea cols='100' >".$o->getUrl()."</textarea><br />";
if ($o->getFormat()=='json') {  
    $result = json_decode($raw);
} else {
    $result = htmlspecialchars($raw);
}
 
echo "<h2>Images</h2>";
foreach($result->SearchResponse->Image->Results as $value) {    
    printf('<a href="%s"><img src="%s" /></a>',$value->Url,$value->MediaUrl);
}
echo "<br />";
echo "<h2>Links</h2>";
foreach($result->SearchResponse->Web->Results as $value) {
    printf('<a href="%s">%s</a><br />',$value->Url,$value->Title);
}
 
?>
    </body>
</html>

If it works, you should see something that looks like this.

That is a simple example that will get you going and allow you to play with the code. Of course you have to get your API key first. Lines 13, 16, and 18 above are the ones you are going to want to play with. 13 being an API key; without that it won’t work. 16 is the search term, I know I have a couple of Zend Framework related posts on my blog so I used that. Line 18 is the domain limit. I only want to search for Zend Framerwork on my blog. Tinker with those a while and see what results you come up with.

Oh, you may have notices the autoLoader from lines 6-11. Feel free to remove that if you like but you will have to add in all the requires for the classes, subclasses and Exceptions. If you put the library in your path, the auto-loader will take care of making sure you have access to them all.

The API

The Bing API is very straightforward and most importantly, consistent in design. These two facts make it very easy to work with. Actually, there are several options that my wrapper doesn’t yet implement, For this first version, I stuck with the basic Search API but they have separate sub-APIs for Phonebook, News, Translation and others. I hope that future version of this wrapper will implement those.

The Wrapper

There are 37 methods in the wrapper and the vast majority of those are housekeeping methods like getters and setters. The heart of the wrapper is the search() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    /**
     * Attempts to execute the currently-specified search
     * 
     * @return string The results from the query
     * @throws Msft_Bing_Search_Exception
     */
    public function search()
    {
        if (empty($this->appid)) {
            throw new Msft_Bing_Search_Exception('Empty AppId');
        }
 
        if (empty($this->sources)) {
            $this->sources[]='web';
        }
 
 
        $this->url = $this->buildUrl();
 
        if ($stream = @fopen($this->url, 'r')) {
            $output = stream_get_contents($stream);
            fClose($stream);
        } else {
            throw new Msft_Bing_Search_Exception('Problem opening stream');
        }
        // print all the page starting at the offset 10
        return $output;
    } // public function search()

As you can see, we check to make sure we have a appId and throw an exception if we don’t. Then, if you’ve not set which sources to check (web,image,spell are currently implemented) we set a default of web.

We then build the URL, call the URL and either return the results back to you for processing or throw an exception because something went wrong.

That’s really all there is to using it. You can play around with the different options like setting ‘spell’ as a source.

Conclusion

The Bing API is easy to work with, powerful, and since Google doesn’t give you access to this information from an API, unique. The possibilities that this API presents are interesting and I’ll explore a couple in the future. The wrapper should get you started in working with it but as I said, it is not yet complete. If you need some of the features that have yet to be implemented, feel free to send me a patch. :) Most of all I hope you learn something form it. After all it is open source. :)

Until next time,
I <3 |K
=C=

Buffer

Tags: API, bing, microsoft, wrapper

This entry was posted on Tuesday, June 1st, 2010 at 11:00 am and is filed under PHP. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Logging In...

Comments are closed.

  • 26 Replies
  • 4 Comments
  • 0 Tweets
  • 0 Facebook
  • 22 Pingbacks
Last reply was November 18, 2010
  1. Powering Search on PHP Web Sites with Bing - Interoperability @ Microsoft - Site Home - MSDN Blogs
    View June 1, 2010

    [...] and coding styles. So, Cal designed and wrote the code of the library for us, and he has just posted a tutorial with some sample code for PHP developers to quickly get started. Try [...]

  2. Bing Community
    View June 1, 2010

    [...] Bing Search Library for PHP June 01, 2010, 10:44 AM by george | 0 Comments Announcing the new Bing Search Library for PHP, created in conjunction with PHP guru Cal Evans, which is available under an open source BSD license. Not only did Cal design and write the code, but he also posted a tutorial that includes sample code for PHP developers. [...]

  3. Bing Community
    View June 1, 2010

    [...] a simple way to submit queries to and retrieve results from the Bing Engine. The tool comes with a tutorial that includes sample code for PHP developers. Check it [...]

  4. Announcing the Bing Search Library for PHP | Global SEO Solutions Blog
    View June 1, 2010

    [...] a simple way to submit queries to and retrieve results from the Bing Engine. The tool comes with a tutorial that includes sample code for PHP developers. Check it [...]

  5. Bing: librerie open source in PHP | Giovanni Raco
    View June 2, 2010

    [...] completa del SDK di Microsoft per Bing è accessibile soltanto previa login su MSDN, ma un tutorial esaustivo per il wrapper è stato pubblicato dallo stesso Evans, che ha curato personalmente la creazione delle librerie: [...]

  6. ????? ?- Bing ?????????? PHP - ??? ???? ??????????
    View June 2, 2010

    [...] ????? ??????? ??, ???? ????????? ?? Cal Evans, ???? PHP ????, ????? ???? ?????? ??? ??????? ?????? ?????? ?????? ????? ?- PHP. ???? ????? ??????, ???? Carl Evans ????? ?????? ?????? ?? ??????? ??? ?????????. [...]

  7. Bing Search Library for PHP « Teusje
    View June 2, 2010

    [...] source ] [ source2 [...]

  8. Dave
    View June 2, 2010

    I’d love to use this, but can’t even log in to get an API key or sign up for a developer account. Instead it continually loops back to the redirect page. My Live Id login works just fine on live.com (in fact if I go there I’m already logged in) but not on Bing, on any browser, whether I accept all cookies or not. So it might be a super API but if Microsoft can’t get a simple Passport login working after all these years I can’t have much confidence in any API they produce in the long term.

  9. Cal Evans
    View June 2, 2010

    Dave,

    Strange. You are correct. I have alerted my friends at Microsoft to see what can be done to fix it.

    =C=

  10. PHP Klasse für die Bing API v2
    View June 2, 2010

    [...] Engineer, TopBlogger & Co. Mr. Cal Evans auf seinem Blog seine Bing API Klasse für PHP vorgestellt. Was ihr [...]

  11. Bing: librerie open source in PHP | recomputer.it
    View June 3, 2010

    [...] completa del SDK di Microsoft per Bing è accessibile soltanto previa login su MSDN, ma un tutorial esaustivo per il wrapper è stato pubblicato dallo stesso Evans, che ha curato personalmente la creazione delle librerie: [...]

  12. Bing Search Library for PHP | Innovative Singapore
    View June 4, 2010

    [...] library was created by seasoned PHP developer Cal Evans, who has also posted a tutorial with some sample code for PHP developers to quickly get [...]

  13. WordPress 404 Plugin built on Bing Wrapper | php|architect
    View June 4, 2010

    [...] at my personal blog, I recently posted about the new Bing Search API wrapper I wrote for Microsoft. In the post, I said that I would talk about some of the uses of the wrapper. [...]

  14. ???? ????????: ???? 404 ?? ?????? ???? Bing - ??? ???? ??????????
    View June 5, 2010

    [...] ???? ????????? PHP, ?????? ???? ?????????, ???? ?? ????? Cal Evans ?? ????? Bing 404 for WordPress ?????? ????? ???? 404 ?? ?????? [...]

  15. enlaces, noticias y recursos de interés
    View June 5, 2010

    [...] Wrapper PHP para el API del buscador BING http://blog.calevans.com/2010/06/01/bing-search-api-wrapper-for-php/ [...]

  16. Bing Opens to Developers with Maps SDK & Search Library for PHP | Technology and Web 2.0
    View June 8, 2010

    [...] the creation of the Bing Search Library for PHP – a wrapper built in conjunction with PHP expert Cal Evans that gives developers easy access to the Bing Search API via PHP. Microsoft seems to be embracing [...]

  17. Bing Opens to Developers with Maps SDK & Search Library for PHP
    View June 8, 2010

    [...] announced the creation of the Bing Search Library for PHP – a wrapper built in conjunction with PHP expert Cal Evans that gives developers easy access to the Bing Search API via PHP. Microsoft seems to be embracing [...]

  18. the hive » Bing Opens to Developers with Maps SDK & Search Library for PHP
    View June 8, 2010

    [...] announced the creation of the Bing Search Library for PHP – a wrapper built in conjunction with PHP expert Cal Evans that gives developers easy access to the Bing Search API via PHP. Microsoft seems to be embracing [...]

  19. TekJoos - TekJoos
    View June 8, 2010

    [...] the creation of the Bing Search Library for PHP – a wrapper built in conjunction with PHP expert Cal Evans that gives developers easy access to the Bing Search API via PHP. Microsoft seems to be embracing [...]

  20. Take Advantage of Bing to Handle 404 Errors « WordPress on Microsoft
    View June 15, 2010

    [...] you’re interested in digging deeper, Cal has another article that talks about using the Bing Search Library with some sample [...]

  21. Bing Powered 404 for non-WordPress websites | php|architect
    View June 17, 2010

    [...] after my last post on using the Bing Search Wrapper for handing 404 errors in WordPress I had several people tell me that while they liked the idea, they didn’t want to install [...]

  22. 10 Basic Tips for Improving WordPress Themes « Andrei Melencovici Graphic and Web Design Blog
    View October 16, 2010

    [...] Finally, if you’re interested in the Bing API (which is being currently used for one of the largest WordPress blogs in the world, Mashable), have a look at this tutorial named Bing Search API wrapper for PHP. [...]

  23. 10 Basic Tips for Improving WordPress Themes | Putra Kuningan
    View October 17, 2010

    [...] Finally, if you’re interested in the Bing API (which is being currently used for one of the largest WordPress blogs in the world, Mashable), have a look at this tutorial named Bing Search API wrapper for PHP. [...]

  24. Digital Caliper 
    View October 17, 2010

    Bing microsoft is the best investment of Bill Gates~`;

  25. 10 Basic Tips for Improving WordPress Themes | BJD Productions Blog
    View October 26, 2010

    [...] Finally, if you’re interested in the Bing API (which is being currently used for one of the largest WordPress blogs in the world, Mashable), have a look at this tutorial named Bing Search API wrapper for PHP. [...]

  26. Mike
    View November 18, 2010

    Straight forward and relatively easy to set up thanks to the Code Library and your instructions Is the search restricted to 50 and is it possible to paginate the results.

  • Friends of mine

  • My Latest Book


    Avoiding a Goat Rodeo

  • Follow me on twitter!

  • RSS PHP Podcasts

    • Episode 7: Web Sockets Are Fast
    • Better Documentation for PHP internals – Lately in PHP podcast episode 35
    • Episode 31: Feline Tooth Extraction
    • Episode #2 – Adam Culp
    • Episode 6: PSR-X and the Mexican Standoff
    • Episode 109: Typescript and a bit more…
    • A Better PHP Feature Voting Process – Lately in PHP podcast episode 34
    • Episode 30: It’s Episode 30, you guys
    • PHP Innovation Award Winner of 2012 – Lately in PHP podcast episode 33
    • Episode 29: Snappy Answers to Stupid Questions

  • Me, elsewhere on the Web

    • Best web design company
    • Cal Evans Dot Com
    • Cyrano’s Apprentice
    • Evans Internet Construction Company
    • My Life as a Child
    • PHP Podcasts

  • Categories

    • Apache
    • BlogBling
    • Blogging
    • Book Review
    • codeworks
    • Entertainment
    • Entrepreneurship
    • Flex
    • Humor
    • JavaScript
    • Long Form
    • Management
    • Marketing
    • Me, elsewhere on the Web
    • PHP
    • podcasting
    • Programming
    • SQL
    • Technology
    • Web 2.0
    • wordpress
    • WordPress Plugins
    • writing
    • zend framework


Postcards From My Life is proudly powered by WordPress
Entries (RSS) and Comments (RSS).