Spell check with Zend_Json_Server & pspell

An application I’ve been working on has had a desire for spell check capabilities for some time now. As most browsers
provide native methods for this, it has remained on the back burner until now.

I decided to use Zend_Json_Server for a few reasons:

  1. I wanted to avoid the overhead required to bootstrap and route requests in my MVC Zend_Framework app
  2. I wanted to tinker with Zend’s easy to use JSON-RPC magic
  3. I try to avoid XML, and thus XML-RPC, as much as possible

Requirements

Your server requires the following for the JSON-RPC server to work:

To use the javascript client (optional):

Files

SpellCheck.php

This class exposes three methods via the JSON-RPC interface: check, suggest, and checkText. As you can see,
check and suggest are simple wrappers for pspell_check and pspell_suggest respectively. They each operate on
only a single word.

The checkText method combines the features of both check and suggest, and works on strings consisting of an
arbitrary number of words. It also returns an object detailing all the spelling errors found, as well as the top five
suggestions for them.

json-rpc.php

This is the wonderfully simple class that sets up our Zend_Json_Server and handles requests. I love that Zend_Json
allows me to do this in only 20 lines of code.

spellcheck.js (optional)

Usage

The usage examples will assume you are using the Prototype client shown above, though any client could be used. They
also assume you have firebug installed, and thus can use the console.log() method.

Example 1

This checks if the word ‘sevne’ is a properly spelled word.

Output

The output shows that the result is false, it is not a correctly spelled word.

Example 2

This asks for suggested spellings for ‘sevne’.

Output

In this case the result is an array of the forty most likely substitutes for this word.

Example 3

This is likely the most useful usage of all, as it avoids the need for multiple calls to the server.

Output

The result in this case is a slightly more complex JSON Object than the other examples.

I’ll do my best to explain this clearly.

  • result is a JSON Object with a single property ‘c’ (corrections).
  • result.c is an Array of corrections
  • each correction is an Object with the following properties
Property Description
o The offset of the misspelled word from the beginning of the text
l The length of the misspelled word
t An Array of the top five suggestions for the misspelled word

The syntax of the checkText method was inspired by Google’s spell check API that is part of the Google Toolbar.
My thanks to Paul Welter for reverse engineering it and posting the results.

Conclusion

This wraps up my fun, though admittedly simple, example of Zend_Json. (I think I spent more time on this blog post than the actual code).

No comments yet.

Leave a Reply