I have recently been working on a little out of hours PHP project called “Dummy“. The code is almost complete, apart from the obligatory prettifying of indents and comments, which means it’s time to turn my attention to the online documentation.
As part of the “How to Use” page I need to show small PHP code examples. I also want them to look very readable and be easy to copy and paste. Hand cranking each code snippet using <span>’s, spaces and CSS clearly isn’t the way to go, there has to be an easy way.
Server Side Options
Having used Pygments (a Python syntax highlighter) I had a quick look for PHP server side solutions and found two native PHP functions that could work.
Client Side Options
Here’s an example of a PHP code snippet using SyntaxHighlighter
In order to apply highlighting to a section of HTML it’s recommended to wrap your example in <pre> tags to preserve the formatting. The final stage is to apply a pre-defined relevant CSS class to the <pre> tag.
There’s support for a huge list of languages including:
- Plain Text
- Visual Basic
SyntaxHighlighter also provides a nice pop up tool-tip (look at the right hand side of a code example when hovering over it) enabling you to view the code in a blank page, copy it to the clipboard or print it.
There are undoubtedly other solutions out there, if you have a preferred one that works for you please link it up in the comments.