Skip to content
Related Articles
Open in App
Not now

Related Articles

How to parse HTML file in PHP ?

Improve Article
Save Article
Like Article
  • Last Updated : 28 Mar, 2022
Improve Article
Save Article
Like Article

In this article, we will learn to parse HTML in PHP.

What is parsing?

Generally parsing is converting one data type to another. It means how we can convert various data types to HTML. For example: Converting string to HTML.

Why do we need parsing?

To add the dynamic data (HTML content) at a certain point in PHP code, we need parsing. For example: For adding the data (info) in the form of HTML, we need to make that dynamic template in string and then convert it to HTML.

How should we do parsing?

We should use loadHTML() function for parsing.


loadHTML(string $source,int $options=0)


  • $source: This variable is the container of the HTML code which you want to parse,
  • $options: You may use the options parameter to specify additional Libxml parameters.

Return value: It returns true on success or false on failure. 

Example 1:


  $doc = new DOMDocument();
  $doc->loadHTML("<html><body><h1>Parsing Html in PHP</h1></body></html>");
  echo $doc->saveHTML();


Parsing Html in PHP

Example 2:               


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
    $res = '
    <table id="tablepress-3" style="width:100%">
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>Centro commercial Moctezuma</td>
        <td>Francisco Chang</td>
    $dom = new DomDocument();
    @ $dom->loadHTML($res);
    $table = $dom->getElementById('tablepress-3');
    $child_elements = $table->getElementsByTagName('tr');
    $row_count = $child_elements->length ;
    echo "No. of rows in the table is " . $row_count;


No of rows in the table is 3

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!