C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » PHP

Display source code of the website with PHP

In this article, we will learn how to delete an element from an array in PHP? There are 2 ways of deleting an element from the array in PHP which are using unset() and array_splice().
Submitted by Abhishek Pathak, on November 05, 2017

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,

Code

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

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.





Sponsored Links




COMMENTS