Skip to content

Instantly share code, notes, and snippets.

@atbradley
Created December 1, 2016 18:37
Show Gist options
  • Save atbradley/dc41f0726e99748ec2294e7ee488144a to your computer and use it in GitHub Desktop.
Save atbradley/dc41f0726e99748ec2294e7ee488144a to your computer and use it in GitHub Desktop.
Simple use of the Bing Spell Check API in PHP
<?php
// See https://www.microsoft.com/cognitive-services/en-us/bing-spell-check-api for API details.
namespace bing\spellcheck;
require_once('conf/base.conf.php');
function _getSuggestions($input) {
$subkey = MICROSOFT_COGNITIVE_API_KEY;
$cl = curl_init('https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?mode=proof&mkt=en-us');
curl_setopt($cl, CURLOPT_POST, true);
curl_setopt($cl, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Ocp-Apim-Subscription-Key: $subkey"));
curl_setopt($cl, CURLOPT_POSTFIELDS, "Text=$input");
curl_setopt($cl, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($cl);
curl_close($cl);
$ret = json_decode($ret, true);
return $ret;
}
function correctText($input) {
$corrections = _getSuggestions($input);
$outp = $input;
if ( key_exists('flaggedTokens', $corrections) ) {
foreach ( $corrections['flaggedTokens'] as $c ) {
$outp = substr_replace($outp, $c['suggestions'][0]['suggestion'],
$c['offset'], strlen($c['token']));
}
}
return $outp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment