PHP – DOM Parser

By | October 2, 2021
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.



   $html = ' 
         <h2>Courses information</h2> 
         <table border = "0"> 
   /*** creating a new dom object ***/ 
   $dom = new domDocument; 

   /*** loading the html into the object ***/ 

   /*** 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 />'; 


Designation: Computer
Manager: Gopal

Designation: Science
Manager: Satish

Designation: Maths
Manager: Raju

People are also reading:

Leave a Reply

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