Menu

Google Code Prettify

I have played with various WordPress plugins for code syntax highlighting, but recently helped answer a query with regards syntax highlighting in other projects using Google Code Prettify.

If you store your code samples in a MySQL database, the trick is to store them as html entities. In other words, the following PHP code:

PHP

1

2

3

<?php

//comment

?>

Should look like this in your database table:

1

&lt;?php// comment ?&gt;

When the code sample is then retrived from the table and displayed in HTML, the HTML entities are displayed as the characters they represent in the browser, rather than being treated as mark-up in the browser.

To do this create a form to add data to your table. In your form processing script, the key is to use the PHPhtmlentities():

PHP

1

$code_sample=htmlentities($_POST['code_sample']);

Then, when retrieving the code sample from the database, you will need this in your HTML<head>: