PHPDOM解析

PHPDOM解析 首页 / PHP入门教程 / PHPDOM解析

用PHP5.X版本编写的HTML Dom解析器。 Dom Parser非常擅长处理XML和HTML。 Dom解析器基于树进行传播,在访问数据之前,它将把数据加载到dom对象中,并将数据更新到Web浏览器。下面的示例显示了如何在Web浏览器中访问HTML数据。

<?php 
   $html=' 
      <head> 
         <title>Learnfk</title>
      </head> 
   
      <body> 
         <h2>Course details</h2> 
      
         <table border="0"> 
            <tbody> 
               <tr> 
                  <td>Android</td> 
                  <td>Gopal</td> 
                  <td>Sairam</td> 
               </tr> 
         
               <tr> 
                  <td>Hadoop</td> 
                  <td>Gopal</td> 
                  <td>Satish</td> 
               </tr> 
         
               <tr> 
                  <td>HTML</td> 
                  <td>Gopal</td> 
                  <td>Raju</td> 
               </tr> 
         
               <tr> 
                  <td>Web technologies</td> 
                  <td>Gopal</td> 
                  <td>Javed</td> 
               </tr> 
         
               <tr> 
                  <td>Graphic</td> 
                  <td>Gopal</td> 
                  <td>Satish</td> 
               </tr> 
         
               <tr> 
                  <td>Writer</td> 
                  <td>Kiran</td> 
                  <td>Amith</td> 
               </tr> 
         
               <tr> 
                  <td>Writer</td> 
                  <td>Kiran</td> 
                  <td>Vineeth</td> 
               </tr> 
            </tbody> 
         </table> 
      </body> 
   </html> 
   '; 
   /*** a new dom object ***/
   $dom=new domDocument; 
   
   /*** load the html into the object ***/
   $dom->loadHTML($html); 
   
   /*** discard white space ***/
   $dom->preserveWhiteSpace=false; 
   
   /*** the table by its tag name ***/
   $tables=$dom->getElementsByTagName('table'); 
   
   /*** get all rows from the table ***/
   $rows=$tables->item(0)->getElementsByTagName('tr'); 
   
   /*** loop 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 'Team: '.$cols->item(2)->nodeValue; 
      echo '<hr/>'; 
   }
?> 

它将产生以下输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/php/php-dom-parser-example.html

来源:LearnFk无涯教程网

DOM Parser 示例

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

中间件核心技术与实战 -〔丁威〕

自动化测试高手课 -〔柳胜〕

编程高手必学的内存知识 -〔海纳〕

如何读懂一首诗 -〔王天博〕

实用密码学 -〔范学雷〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

互联网人的英语私教课 -〔陈亦峰〕

MySQL实战45讲 -〔林晓斌〕

程序员进阶攻略 -〔胡峰〕

好记忆不如烂笔头。留下您的足迹吧 :)