5 Easy Ways to Display Syntax Highlighted PHP Code

Published Wednesday, December 5, 2007 @ 11:17 am • 1 Response

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.

The PHP Functions

All of the syntax-highlighting methods presented in this article 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.

Well, that does it for this article! I have also created a page summarizing these 5 methods, along with quick links to their respective examples.

References



Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

mmmm, dark chocolate..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Nyx: Happy to have helped! Love your site....
  • dockside: Hi i want to use this code on my blog. but not for all post. I want 3 or 4 full posts and then post in double column How?...
  • NZ Beats: Got it working using the following: http://www.nzbeats.com/?feed=rss2&category_name=album-review...
  • Paul: Holy crap, you just saved my A$$! Thank you!...
  • free games: Google have a content distribution network here http://code.google.com/apis/ajaxlibs/documentation/#AjaxLibraries where you ca...
  • free games: Found this (untested) for those that just want https For HTTPS: var pageTracker = _gat._getTracker("UA-XXXX-1"); pageTracker...
  • H5N1: The question is very hard. No way to solve it in only few words :) First of all you need a Linux. OK. But Linux it's only a Kerne...
  • gowers: wow, your theme is so great, I like it...
  • Eric Ferraiuolo: Like some people are commenting, a virtual solution is going to be the easiest to get going with the least number of issues. I would ...
  • Brent Terrazas: Thanks for the mention, I currently am running Ubuntu Server 8.04 on VMWare Fusion beta (it's a free beta download.. check it out fo...

Read more recent comments..