highlight_file() function in PHP

The highlight_file() function outputs a file with the PHP syntax highlighted using colors. It's useful for displaying PHP source code in a readable, formatted way on web pages.

Syntax

highlight_file(file, return)

Parameters

  • file − The file name to display. Can be a relative or absolute path to the PHP file.

  • return − Optional boolean parameter. If set to true, the function returns the highlighted code as a string instead of printing it directly. Default is false.

Return Value

Returns true on success or false on failure when the return parameter is false. When return is true, it returns the highlighted code as a string.

Example 1: Direct Output

Let's create a sample PHP file and highlight its contents ?

<?php
    // sample.php contains:
    // <?php
    // $message = "Hello World";
    // echo $message;
    // ?>
    
    highlight_file("sample.php");
?>

Example 2: Returning as String

You can capture the highlighted code as a string for further processing ?

<?php
    $highlighted_code = highlight_file("sample.php", true);
    echo "<h3>PHP Code:</h3>";
    echo $highlighted_code;
?>

Output

The function outputs HTML with colored syntax highlighting. PHP keywords appear in blue, strings in red, comments in orange, and variables in purple.

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php<br />$message&nbsp;</span>
<span style="color: #007700">=&nbsp;</span>
<span style="color: #DD0000">"Hello World"</span>
<span style="color: #007700">;<br />echo&nbsp;</span>
<span style="color: #0000BB">$message</span>
<span style="color: #007700">;<br />?&gt;</span>
</span></code>

Conclusion

The highlight_file() function is perfect for displaying PHP source code with syntax highlighting on web pages. Use the return parameter to capture output as a string when you need additional processing.

Updated on: 2026-03-15T07:36:46+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements