Hello World!

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:


Should look like this in your database table:

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

When the code sample is then retrieved 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 PHP htmlentities():

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

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

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>

In your HTML <body>:

echo '<pre class="prettyprint lang-'.$row['language'].'">'.$row['code_sample'].'</pre>';


By foxbeefly

PHP / MySQL Developer. HTML, CSS and some JavaScript.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.