Display source code of the website with PHP

belongs to collection: PHP Miscellaneous


PHP is a server side scripting language and provide dynamic content to the webpages. It builds the source code for the webpage that is then parsed by the browser to render the webpage. But we can also find the source code of a webpage with PHP and in this article; we will learn how to display the source code of the website with PHP?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Following is the code that will be explained after the program,


// display source code

// get the url as file
$lines = file('http://google.com/');

//Loop each line as line_num
foreach ($lines as $line_num => $line) {
	// loop through each line and prepend line numbers and echo it
	echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";

Firstly, we have the $lines variable which will keep the result of the source code generated by the file() built-in method of PHP. The file method simply takes a URL and generates the source code file of it. This is then kept as an array line by line and stored inside the lines variable which we can use to display the source code line by line.

To do that, we need to run a loop on this array and echo a line number along with one line. This can be achieved using the forEach loop which takes each element of an array $lines as $line_num associated with $line. We then echo out the line number in bold using the HTML tags in between since this page is sent by server and finally rendered on the browser. We use the htmlspecialchars() in order to safely display the HTML tags.

This program helps us to show the source code of an URL line by line to the user? If you like the article, please share your thoughts in the comments below.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Miscellaneous

This question belongs to these collections

Similar questions

need a help?

find thousands of online teachers now
Get the contents of a directory in PHP... >>