Perishable Press

PHP Syntax-Highlighting Examples

This page links to several examples of PHP syntax-highlighting referred to in the article, 5 Easy Ways to Display Syntax Highlighted PHP Code.

Highlight an entire file

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

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.
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 in this example is the only code needed to highlight any PHP document.
Unobtrusive syntax-highlighting for PHP files and strings
This method requires no tampering with the target file. Simply employ the function described in the original article and you’re good to go. As a bonus, this technique generates valid XHTML markup.

Highlight an individual string

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

Default syntax-highlighting for any PHP string
Using this code: <?php highlight_string('<?php phpinfo(); ?>'); ?>, we get this output: <?php phpinfo(); ?> . The result is syntax-highlighted output of the input string. Note that the output looks better (i.e., as intended) on a white background.
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;
}
?>
For more information on this method, check out the complete article on PHP Syntax Highlighting Methods. Meanwhile, click here to see this code in action.

« Return to article

References

All Contents Copyright © 2013 Perishable Press