5 Easy Ways to Display Syntax Highlighted PHP Code

A great to way to share your PHP code with visitors is to display it directly in the browser with automatically generated syntax highlighting. Here is a screenshot showing an example of syntax-highlighted PHP code:

[ Screenshot: PHP code snippet in syntax-highlighted form ]

Displaying your PHP scripts in syntax-highlighted form is an excellent way to share source code details directly with your readers. Rather than zipping the script and requiring users to download, unzip, and open the file in an editor, displaying your code directly saves you and your visitors time, effort, and hassle. Plus, in my opinion, looking at syntax-highlighted PHP code is a beautiful sight, day or night ;)

In this article, we will explore 5 different ways to display the syntax-highlighted source of your PHP scripts. Three of the methods are designed to highlight entire files, and the other two are aimed directly at highlighting individual strings of PHP code. All of these methods employ PHP’s built-in syntax highlighter. Note that all of the code examples and files for this tutorial are available for free download at the end of the article.

The PHP Functions

All of the syntax-highlighting methods presented in this tutorial rely on one of two core PHP functions, highlight_file() and highlight_string():

  • highlight_file() — displays the source code for a specific PHP file
  • highlight_string() — displays the source code for a specific string of PHP code

Each of these functions highlights the target PHP code according to a predefined set of colors, applied via inline CSS applied via <font> elements. The function highlight_file() uses the name of the target file as the parameter and returns the file contents in syntax-highlighted form. Similarly, highlight_string() uses a specific string of code as the parameter and returns it with syntax highlighting applied.

One last note before we dig into the various techniques: use caution and a dash of common sense when it comes to displaying the source of your PHP scripts. Make sure that you are not unintentionally revealing sensitive data such as passwords, user logins, database credentials, etc. With that in mind, let’s get on with it..

PHP Syntax Highlighting for Individual Files

Using the PHP function highlight_file(), we can generate “a syntax-highlighted version of the given PHP [file] using the colors defined in the built-in syntax highlighter for PHP.1

Syntax-highlighting via .phps extension

This method is dead-easy if enabled on your server. Simply change the file extension from .php to .phps. Be careful not to reveal the source of any secure data, such as passwords, etc. If syntax highlighting doesn’t seem to be working with this method, try adding the following directive to your domain’s httpd.conf or to your site’s root (or other target directory) htaccess file:

AddType application/x-httpd-php-source .phps

PHP syntax-highlighting via FILE constant

Another easy method for highlighting the syntax of a PHP file is to call the highlight_file() function at the beginning of the file. The first line displayed via the preceding link is the only code needed to highlight any PHP document. Simply add the following code to the target file and open in a browser to see the syntax-highlighted source:

<?php highlight_file( __FILE__ ); ?>

(X)HTML-validating syntax-highlighting for PHP files and strings

This method is nice because it requires no tampering with the target file, and also generates valid XHTML markup for the highlighted source code. To use this method, begin by placing the following code into a blank .php file and name it something like “highlighter.php”:

<?php 

function string_syntax_xhtml( $string, $return = false ) {
	$highlight = highlight_string( $string, true );
	$replace   = str_replace(
		array( '<font color="', '</font>' ),
		array( '<span style="color: ', '</span>' ),
		$highlight 
	);
	if( $return ) {
		return $replace;
	}
	echo $replace;
	return true;
}

function file_syntax_xhtml( $path, $return = false ) {
	return string_syntax_xhtml( file_get_contents( $path ), $return );
}

echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><title></title></head><body>';
string_syntax_xhtml( file_get_contents( 'file_example.php' ) );
echo '</body></html>';

?>

To use this script, edit the “file_example.php” in the penultimate line to reflect the location of your target file. Then, to display the syntax-highlighted source-code of the target file, create a link to the file containing the script (i.e., highlighter.php). That’s all there is to it. Whenever a user clicks on the link to the highlighter.php file, the source code of the target PHP file will be displayed in the browser.

PHP Syntax Highlighting for Individual Strings

Using the PHP function highlight_string(), we can generate “a syntax-highlighted version of the given PHP [string] using the colors defined in the built-in syntax highlighter for PHP.2

Default syntax-highlighting for any PHP string

For on-the-fly syntactical highlighting of PHP strings, we can use PHP’s native function highlight_string(). Using this function couldn’t be easier, simply use this code:

<?php highlight_string('<?php phpinfo(); ?>'); ?>

..and replace the example argument (“<?php phpinfo(); ?>”) with the PHP string of your choice. When the script is processed it will apply syntax highlighting to the input string similar to the following HTML source code for this example (note that the opening and closing <?php and ?> are required with the input string):

<font color="#000000">
   <font color="#007700">&lt;?</font>
   <font color="#0000bb">php&nbsp;phpinfo</font>
   <font color="#007700">();&nbsp;</font>
   <font color="#0000bb">?&gt;</font>
</font>

String syntax-highlighting with automatic quote-escaping

Generating highlighted code from strings of PHP code using highlight_string requires us to escape quotes (e.g., ' , " ). Depending on your input string, escaping e\v\e\r\y quote may prove tedious and boring, opening wide the doors to potential error. Fortunately, the following technique eliminates the frustration by cleaning things up automagically:

<?php code(); ?>
          $string = '[ place your "highly quoted" PHP string here ]';
<?php code(); ?>

<?
function code() {
          static $on = false;
          if ( !$on ) {
               ob_start();
          } else {
               $buffer = "<?\n" . ob_get_contents() . "?>";
               ob_end_clean();
               highlight_string( $buffer );
          }
          $on = !$on;
}
?>

To use this script, place your target string between the “<?php code(); ?>” declarations and paste into any PHP file. Calling this file will then generate the syntax-highlighted source of the entire code string. Special thanks to phella.net for sharing this technique in the php.net forums 2.

Download the demo pack

Well, that does it for this article! I have also put together a demo pack containing all of the files and code for this tutorial. To use the demo, download the following zip file and upload its unzipped contents to any PHP-enabled server (i.e., PHP required).

Demo Pack: PHP Syntax Highlighting – Version 1.0 (8 kB zip)

References