PHP – DOM Parser

By | August 20, 2020
PHP - DOM Parser

DOM parsers work well with both XML and HTML. This parser is tree-based where DOM first loads the data into the Dom object then it will load the data to the browser. 

Below example will help you to understand how to access the HTML data in the web browser.

Vamware

Example:

<?php 
   $html = ' 
      <head> 
         <title>DATA</title>
      </head> 
      <body> 
         <h2>Courses information</h2> 
         <table border = "0"> 
            <tbody> 
               <tr> 
                  <td>Computer</td> 
                  <td>Gopal</td>
               </tr> 
               <tr> 
                  <td>Science</td> 
                  <td>Satish</td> 
               </tr> 
               <tr> 
                  <td>Maths</td> 
                  <td>Raju</td> 
               </tr> 
             </tbody> 
         </table> 
      </body> 
   </html> 
   '; 
  
   /*** creating a new dom object ***/ 
   $dom = new domDocument; 

   /*** loading the html into the object ***/ 
   $dom->loadHTML($html); 

   /*** ignoring white space ***/ 
   $dom->preserveWhiteSpace = false; 

   /*** the table by its tag name ***/ 
   $tables = $dom->getElementsByTagName('table'); 
 
  /*** retrieve all rows from the table ***/ 
   $rows = $tables->item(0)->getElementsByTagName('tr'); 
 
  /*** looping over the table rows ***/ 
   foreach ($rows as $row) {
   
   /*** get each column by tag name ***/ 
      $cols = $row->getElementsByTagName('td'); 
    
      /*** echo the values ***/ 
      echo 'Designation: '.$cols->item(0)->nodeValue.'<br />'; 
      echo 'Manager: '.$cols->item(1)->nodeValue.'<br />'; 
      echo '<hr />'; 
   }
?>

Output:

Designation: Computer
Manager: Gopal

Designation: Science
Manager: Satish

Designation: Maths
Manager: Raju

Leave a Reply

Your email address will not be published. Required fields are marked *