Working with RTF

The Rich Text Format specification is a text file format that allows some document formatting to be saved in the document using special text tags. In a way, RTF can be considered very similar to HTML in that it stores display and style information for a document. RTF is noticeably less easy to read, and is not designed for hand editing. Instead, most word processing packages should be able to save in RTF format (this includes modern systems such as Microsoft Word 2003) so that documents can be interchanged across word processors and operating systems.

RTF is so named because you can open RTF files and read them in your favourite text editor, as they are simply formatted text. As a result, we can work with them using simple string functions. To give you an idea of what we're working with, here's the contents of an example RTF file:

{\rtf1
\b Hello world! \b0\par
\b Hello world! \b0\par
\b Hello world! \b0\par
}

That is functionally equivalent to the following HTML:

<HTML>
<P><B>Hello world!</B></P>
<P><B>Hello world!</B></P>
<P><B>Hello world!</B></P>
</HTML>

As you can see, HTML is a little more wordy but easier on the eye - and the brain! Complex RTF documents are virtually impossible to read and certainly impossible to understand, which limits its usefulness from a pure generation point of view. However, given that the PHP string-handling functions allow us to manipulate strings without having to worry about the things we do not match, we can pre-create a complex RTF file using a compliant package (e.g. Microsoft Word or OpenOffice.org), write in special keywords where we want to manipulate the text later, and simply replace/adjust those keywords inside our PHP scripts.

For example, we could change our example RTF script to this:

{\rtf1
\b [MESSAGE] \b0\par
\b [MESSAGE] \b0\par
\b [MESSAGE] \b0\par
}

Using a little bit of PHP magic, we can use str_replace() to replace all instances of [MESSAGE] with "Hello world!", "Goodbye Perl!" or anything in between. Using this method you can create complex documents in the RTF format, which, although they will be fairly large in size, will at least be editable by your visitors. There are limits to RTF, however, simply because it is a very basic format - if you want something more complicated, you need to turn to PDF.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Creating PDF documents >>

Previous chapter: Making graphs

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.