1. 開始使用
首先下載解壓縮,然后將simple_html_dom.php文件包含進要編寫的腳本文件中,加載要處理的html,支持三種模式的html加載,分別是『從url中加載,從字符串中加載,從文件中加載』.代碼如下:
- require_once('simple_html_dom.php');
- //從url加載
- $html = file_get_html('http://www.49028c.com');
- //從字符串加載
- $html = str_get_html('<html><body>Hello World!</body></html>');
- //從文件中加載
- $html = file_get_html('example.htm');
- 從字符串加載網上文件需要先從網絡下下載,使用cURL比較好一些,需要在php配置文件中打開php擴展php_curl。
- $url = 'http://www.49028c.com';
- $ci = curl_init();
- curl_setopt($ci,CURLOPT_URL,$url);
- curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
- $result = curl_exec($ch);
2.查找html元素
使用find函數查找,返回包含對象的數組,常見的查找如下.
- //查找超鏈接元素
- $alink = $html->find('a');
- //查找第n個連接元素
- $alink = $html->find('a',5);
- //查找id為main的div
- $mainDiv = $html->find('div[id=main]');
- //查找所有定義了id的div
- $idDiv = $html->find('div[id]');
- //查找所有定義了id的元素
- $idAll = $html->find('[id]');
- //查找樣式類為info的元素
- $classInfo = $html->find('.info');
- //支持嵌套子元素查找
- $ret = $html->find('ul li');
- //查找多個html元素
- $ret = $html->find('a,img,p');
- //....
3.其他
可以使用內置的函數來進行元素的定位,返回父元素parent,返回子元素數組children,返回第一個子元素first_child,返回最后一個子元素last_child,返回前一個相鄰元素prev_sibling,返回后一個相鄰元素next_sibling等.提供簡單的正則表達式來過濾屬性選擇器,類似于[attribute]的格式.
每個對象都有4個基本屬性:
tag — 返回html標簽名
innertext — 返回innerHTML
outertext — 返回outerHTML
plaintext — 返回HTML標簽中的文本
返回元素屬性值:
- //返回$alink的href值
- $link = $alink->href;
通過設置元素的屬性值可以對元素進行添加、修改、刪除操作,代碼如下:
- //刪除url連接
- $alink->href = null;
- //元素的修改
- $ret->outertext = '<div class="nav">' . $ret->outertext . '</div>';
- $ret->outertext = '';
- $ret->outertext = $ret->outertext . '<div>other</div>';
- $ret->outertext = '<div>Welcome</div>' . $ret->outertext;
- -EOF-
新聞熱點
疑難解答