Skip to content
Related Articles

Related Articles

How to parse HTML file in PHP ?

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Mar, 2022

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.

Syntax:           

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

Parameters:

  • $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:

PHP




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


Output:

Parsing Html in PHP

Example 2:               

PHP




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


Output:

No of rows in the table is 3

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!