Wednesday, 8 August 2007

MSN Search API in PHP

Here's some code for accessing the MSN Live Search API from PHP. You can get a developer key here by going to Configure Applications, Create and Manage Application IDs. You'll need a Microsoft Passport to get your key.

You'll need the PHP5 SOAP library enabled (make sure

extension=php_soap.dll
is uncommented in your php.ini).

To run a search on MSN and scrape results, set up a variable called
$msnsoapkey
with your key in it as a string, then call this function with three parameters:

  1. A string of your query - "site:fish.com" or "seo ranter", for example

  2. How many results you'd like, up to a maximum of 50

  3. The offset for the start of results; 0 means give results from number 1 to $querysize; 100 means from 101 to 100+$querysize.




/////
// fetches from search.msn.com results for the query $query, using the API

function fetchMSNResults($query, $querysize, $offset) {
global $msnsoapkey;
static $msnsoap;

// only generate this WSDL proxy once
if (!isset($msnsoap)) {
$msnsoap = new soapclient("http://soap.search.msn.com/webservices.asmx?wsdl");
}

$request = array(
'Request' => array(
'AppID' => $msnsoapkey,
'Query' => $query,
'CultureInfo' => 'en-US',
'SafeSearch' => 'Off',
'Flags' => '',
'Requests' => array(
'SourceRequest' => array(
'Source' => 'Web',
'Offset' => $offset,
'Count' => $querysize,
'ResultFields' => 'Url'
)
)
)
);

$response = $msnsoap->Search($request);

foreach($response->Response->Responses->SourceResponse->Results->Result as $hit) {
$results[] = $hit->Url;
}

return $results;
}


It will return an Array() of Strings, each one containing a result URL. Easy! This is contained by a wrapper function in my code library, which manipulates the
$offset 
and
$querysize
to allow for any number of results to be returned at the courtesy of the MSN API; you can figure one out pretty easily if you need.

1 comment:

Anonymous said...

its really a great resource for website design.

 
Marketing & SEO Blogs - Blog Top Sites sitemap