首頁  >  文章  >  後端開發  >  php使用simple_html_dom解析HTML範例

php使用simple_html_dom解析HTML範例

WBOY
WBOY原創
2016-07-27 16:56:171098瀏覽

本文實例講述了php使用simple_html_dom解析HTML的方法。分享給大家參考,具體如下:

今天寫了兩個爬蟲, 一個使用Python, 一個使用PHP, 說實在, 兩個實現的方式都很方便.

下面說一下使用simple_html_dom這個開源類別來解析HTML程式碼:

1. 下載simple_html_dom:

http://sourceforge.net/projects/simplehtmldom/files/

http://sourceforge.net/projects/simplehtmldom/files/

2. 用法範例:

<&#63;php
// example of how to use basic selector to retrieve HTML contents
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.google.com/');
// find all link
foreach($html->find('a') as $e) 
  echo $e->href . '<br>';
// find all image
foreach($html->find('img') as $e)
  echo $e->src . '<br>';
// find all image with full tag
foreach($html->find('img') as $e)
  echo $e->outertext . '<br>';
// find all div tags with id=gbar
foreach($html->find('div#gbar') as $e)
  echo $e->innertext . '<br>';
// find all span tags with class=gb1
foreach($html->find('span.gb1') as $e)
  echo $e->outertext . '<br>';
// find all td tags with attribite align=center
foreach($html->find('td[align=center]') as $e)
  echo $e->innertext . '<br>';
// extract text from table
echo $html->find('td[align="center"]', 1)->plaintext.'<br><hr>';
// extract text from HTML
echo $html->plaintext;
?>

更多關於PHP相關內容有興趣的讀者可查看本站專題:《PHP編碼與轉碼操作技巧總結》、《php物件導向程式設計入門教學》、《PHP數學運算技巧總結》、《PHP數組(Array)操作技巧大全》、《php字串(string)用法總結》、《PHP資料結構與演算法教程》、《php程式設計演算法總結》、《php正規表示式用法總結》及《php共同資料庫操作技巧總表》

希望本文所述對大家PHP程式設計有所幫助。

以上就介紹了 php使用simple_html_dom解析HTML範例,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn