Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get the source code of a web page using PHP ?

Improve Article
Save Article
  • Last Updated : 08 Feb, 2021
Improve Article
Save Article

Given a webpage, for which we need to find its source code using PHP. For this, we are going to use the PHP htmlspecialchars() function which converts any predefined characters to their subsequent HTML entities.

Example 1: Suppose we take a sample website that looks like the below image, let us see what output would the code produce for the same.

HTML code:


<!DOCTYPE html>
    <meta charset="utf-8">
    <title>SAMPLE WEBSITE</title>
<body style="color: green;">
    <h1>This is a Sample website</h1>
        In this article we will learn 
        how to extract a web page's 
        source code through PHP


Output as source code contents:

Now let us suppose the above website is hosted on a localhost, the code would fail to load the source code in such a case. The output produced would be something similar to this.


Warning: file(file:///D:/Html%20website/gfg%20sample%20website/index.html): Failed to open stream: No such file or directory in C:\xampp\htdocs\programs\source code.php on line 2

Warning: foreach() argument must be of type array|object, bool given in C:\xampp\htdocs\programs\source code.php on line 3

Example 2:


  • Store its elements into an array.
  • Traverse the array using a PHP programming loop.
  • Convert and print each character into its subsequent HTML entity.

PHP code: Below is the implementation of the above approach.


// Storing the elements of the webpage into an array
$source_code = file('');
// 1. traversing through each element of the array
// 2.printing their subsequent HTML entities
foreach ($source_code as $line_number => $last_line) {
    echo nl2br(htmlspecialchars($last_line) . "\n");


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!