Highlight PHP Codes with Line Numbers Using highlight_file () Function
PHP has an awesome function that highlights its own code, means you can highlight PHP codes using a function which is the PHP highlight_string () for string and highlight_file () for a PHP file.
On using this function, the highlighted code never come with line numbers but in this post I’ll show you how I tweak up the function to have line numbers for it. I don’t like code copiers like just copy the codes and get what you want, I will show you step by step on how I achieved this. 🙂
Now in the case am using the highlight_file () function, and also am using the help of the client side to beautify the highlighter and the line numbers. I guess you’ve already added the <html><head>… elements, for the server side comments are in the code below which should be self explanatory 🙂
<html> <head> <title>Syntax Highlighter</title> <style type="text/css"> .syntax-highlight-line { color: #000000; font-size: 12px; float: left; font-family: 'Source Code Pro'; padding-right: 5px; } .syntax-highlight-code { padding-left: 30px; font-family: 'Source Code Pro'; border-bottom: 1px solid #EEEEEE; } </style> </head> <body> <?php //highlighting file and second argument set to true for this function to return the value instead of echoing it $file = highlight_file ( 'shit.php', true ); //does the file really exist? if ( !$file ) { die ( 'Empty file to highlight' ); } //Oh ye, it does else { //since the output is returned as html and new lines are broken with the <br /> tag, let's explode each line to array using <br /> to recognise a new line $file = explode ( '<br />', $file ); //first line number should be 1 right? $i = 1; //Now for each line we are gonna add line number to it and wrap it up with their divs foreach ( $file as $line ) { echo '<div class="syntax-highlight-line">' . $i . '. </div> <div class="syntax-highlight-code">' . $line . '</div><br/>'; //Oh, line number should keep incrementing as long as new line of code still exists $i++; } //that's it }?> </body> </html>
The above should output something like the picture below, goodluck 🙂