Skip to content

highlight_file()

In this article, we will focus on the PHP highlight_file() function. We will provide you with an overview of the function, how it works, and examples of its use.

Introduction to the highlight_file() function

The highlight_file() function is a built-in function in PHP that is used to highlight the syntax of a PHP file. It can be used to display the syntax of a PHP file in a web page or to generate a formatted PHP file for documentation purposes.

The highlight_file() function takes a filename as its argument and generates an HTML representation of the PHP file with syntax highlighting. By default, it outputs the result directly to the browser, but you can capture it as a string using its second parameter.

How to use the highlight_file() function

Using the highlight_file() function is very simple. You just need to call the function and pass the filename of the PHP file that you want to highlight. Here is an example:

How to use the highlight_file() function?

php
<?php
$file = 'example.php';
highlight_file($file);
?>

In this example, we have a variable $file that contains the filename of the PHP file that we want to highlight. We then call the highlight_file() function and pass the filename as an argument. The function generates an HTML representation of the PHP file with syntax highlighting and outputs it to the browser.

Customizing the output

The highlight_file() function has limited built-in customization options. It only accepts a second boolean parameter $return. When set to true, the function returns the highlighted HTML as a string instead of outputting it directly to the browser.

Here is an example of how to capture the output:

Example of capturing output

php
<?php
$file = 'example.php';
$highlighted = highlight_file($file, true);
echo '<pre>' . $highlighted . '</pre>';
?>

If you need advanced customization (such as custom CSS classes, line numbers, or different color schemes), highlight_file() is not the right tool. For highlighting code stored in variables, use highlight_string(). For full control over the output, consider using a third-party library or implementing a custom highlighter with PHP's token_get_all() function.

Conclusion

In conclusion, the highlight_file() function is a straightforward tool for generating formatted PHP code with syntax highlighting. By understanding its actual parameters and limitations, you can effectively use it for basic syntax display or integrate it with external tools for more advanced formatting needs.

Practice

What does the `highlight_file()` function in PHP do?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.