PHP Tutorial

PHP Examples

PHP Practice

Display source code of the website with PHP

Learn, how can we get and display the source code of a webpage/website using PHP?
Submitted by Abhishek Pathak, on November 05, 2017 [Last updated : March 14, 2023]

Getting source code of a webpage

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?

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

PHP code to get source code of a webpage

<?php 
// 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";
}
?>

Code Explanation

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.

More PHP Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.