Dynamic Generation of RTF with PHP
With PHP, you cannot only create web pages dynamically, but also other files you wish to offer on your web
server - e.g. RichText documents (rtf). You do not even need any PHP extensions, just some knowledge about the file format.
Explanation: Generally, you can insert PHP code into every file which has a text-based format. The server only has to know that this format has to be processed using php.
So, how does this work with rtf files? It is easiest if you want to insert dynamic content into a fixed template (content from a form or a database, current date and time etc):
- You create the template with a text processing software (e.g. MS Word or OpenOffice Writer) and create some text as placeholder where you want your dynamic content to appear.
- You open the just created document with an editor which does not interpret the document but displays it as ASCII text.
- You look for your placeholder and replace it with your PHP code.
- You insert the following line to the beginning of the file: <?php Header('Content-Type: application/rtf')?>
Now you still have to tell your server to process rtf files with PHP. On Apache servers, you can do this by creating a file named .htaccess
in the directory where the rtf file is located (yes, a file like those normally used for defining access rights). The .htaccess has to have the
AddType application/x-httpd-php .rtf
Prerequisite for this to work, however, is that the Apache configuration allows the use of the AddType directive (AllowOverride FileInfo or AllowOverride All in the Apache configuration).
Here I give an example: The template was created using OpenOffice Writer (screenshot of the template). This is the template's content as plain text:
Now the text "And here we will insert the current date." should be replaced by a current timestamp (date and time). So the template is changed to contain the corresponding lines of PHP code:
That's it! The document that is received from the web server can be seen in this screenshot.