Basic Usage - GeSHi/geshi-1.0 GitHub Wiki

Use of GeSHi is very easy. Here’s a simple example:

//
// Include the GeSHi library
//
include_once 'geshi.php';
 
//
// Define some source to highlight, a language to use
// and the path to the language files
//
 
$source = '$foo = 45;
for ( $i = 1; $i < $foo; $i++ )
{
  echo "$foo\n";
  --$foo;
}';
$language = 'php';
 
//
// Create a GeSHi object
//
 
$geshi = new GeSHi($source, $language);
 
//
// And echo the result!
//
echo $geshi->parse_code();

As you can see, there’s only three really important lines:

include_once('geshi.php')

This line includes the GeSHi class for use

$geshi = new GeSHi($source, $language);

This line creates a new GeSHi object, holding the source and the language you want to use for highlighting.

echo $geshi->parse_code();

This line spits out the result :)

So as you can see, simple usage of GeSHi is really easy. Just create a new GeSHi object and get the code!

Since version 1.0.2, there is a function included with GeSHi called geshi_highlight. This behaves exactly as the php function highlight_string() behaves - all you do is pass it the language you want to use to highlight and the path to the language files as well as the source. Here are some examples:

// Simply echo the highlighted code
geshi_highlight($source, 'php', $path);
 
// Get the code back, for use later
$code = geshi_highlight($source, 'java', $path, true);
 
// Check if there is an error with parsing this code
 
ob_start();
$result = geshi_highlight($source, 'perl', $path);
$code = ob_get_contents();
 
ob_end_clean();
if ( !$result )
{
    // There was an error with highlighting...
}
else
{
    // All OK :)
}

However, these are really simple examples and doesn’t even begin to cover all the advanced features of GeSHi. If you want to learn more, continue on to section 3: Advanced Features.