Spell Check in PHP with Yahoo API

by Php Ninza on July 28, 2009


Spell Check is a very nifty feature that a developer need to know , Especially when creating htaccess rewrite rules dynamically you will not want your URL’s to have index with wrong spellings , As this will hamper your SEO performance.

Here is a very easy tool that a developer can implement in their applications for checking the spellings, I have used this API when the users are searching on my web app !, This search make SEO URL’s which i don’t want to index in a incorrect manner.



For using Yahoo SpellCheck API first you need to register a Application ID ! This Application ID will be used to monitor your API calls .

We will be simply making a function here named spell_check which will check the spellings wherever you require.

Let’s create a file name spellcheck.php and put the code given below in that file.

< ?php
function spell_check ($query)
{
// Substitute this application ID with your own application ID provided by Yahoo!.
$appID = "Your App Id here";

// URI used for making REST call. Each Web Service uses a unique URL.
$request = "http://search.yahooapis.com/WebSearchService/V1/spellingSuggestion?appid=$appID&query=".urlencode($query);

// Initialize the session by passing the request as a parameter
$session = curl_init($request);

// Set curl options by passing session and flags
// CURLOPT_HEADER allows us to receive the HTTP header
curl_setopt($session, CURLOPT_HEADER, true);

// CURLOPT_RETURNTRANSFER will return the response
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// Make the request
$response = curl_exec($session);

// Close the curl session
curl_close($session);

// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
        $xml = null;
}

// Create a SimpleXML object with XML response
$simple_xml = simplexml_load_string($xml);

// Traverse XML tree and save desired values from child nodes
	$data = $simple_xml->Result;
	return $data;
}
?>

Above code uses Curl to fetch the API url contents and return the correct spelling , Please change $appID variable with your yahoo App id key.

Once you have created spellcheck.php, Just call this file in a php page and use spell_check function to parse the wrong spellings and correct the data.

Example given below

include ("spellcheck.php");
$correct_spelling = spell_check($wrong_spelling);
echo $correct_spelling;

Technorati Tags: , , ,

blog comments powered by Disqus

Previous post:

Next post:

BidVertiser