Search the blog

This tutorial will show you how to take a URL, read in the source code and then format it. The code listed will assume that you are passing the URL as an encoded variable via GET with the name u.

First off here are the CSS styles you’ll need to format the code (you should customise these to suit your needs):

body {

    background-color: #111111;
    font-family: Courier New, Courier, mono;
    font-size: 11px;
    color: #66CCFF;

}

span { color: #FFFFFF !important; }

.linenumber { color: #FF9900; }

em { color: #666666; }

h3 { 

    font-family: Arial, sans-serif; 
    text-decoration: none;

}

.codelink {

    font-family: Arial, sans-serif;
    text-decoration: none;
    font-size: 10px;
    color: #EEEEEE;
}

.codelink:hover {

    text-decoration: underline;
    color: #66CCFF;

}

Now we to read the HTML in via a HTTP file stream. This is very easy to do, we just use PHP’s file() function.

<?php

$url    = "http://" . $_SERVER['HTTP_HOST'] . "/" . $_GET["u"];
$lines = file($url);

?>

Now we’ve got the HTML stored in a variable we need to use htmlentities() to make the source code display the same way through the browser as it would look like if we were to view the source. We then do some string replacement to insert out CSS styles into the HTML so that the tags and the tag contents are different colours:

<?php

foreach($lines as $line_num => $line) {

    $line = htmlentities($line);
    $line = str_replace("<", "<span><", $line);
    $line = str_replace(">", "></span>", $line);
    $line = str_replace("<!–", "<em><!–", $line);
    $line = str_replace("–>", "–></em>", $line);

    echo "<span class=\"linenumber\">Line <strong>$line_num </strong></span> : " . $line . "<br/>\n";

}

?>

That’s all there is to it! If you saved this page as viewsource.php then you’d link to it like this:

<a href="viewsource.php?u=<?= $_SERVER["PHP_SELF"] ?>">View Source</a>
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.