用php解析html的實現代碼_PHP教程

來源:互聯網
上載者:User
最近想用php寫一個爬蟲,就需要解析html,在sourceforge上找到一個項目叫做PHP Simple HTML DOM Parser,它可以以類似jQuery的方式通過css選取器來返回指定的DOM元素,功能十分強大。
首先要在程式的開始引入simple_html_dom.php這個檔案
複製代碼 代碼如下:
include_once('simple_html_dom.php');

PHP Simple HTML DOM Parser提供了3種方式來建立DOM對象
複製代碼 代碼如下:
// Create a DOM object from a string
$html = str_get_html('Hello!');
// Create a DOM object from a URL
$html = file_get_html('http://www.google.com/');
// Create a DOM object from a HTML file
$html = file_get_html('test.htm');

得到DOM對象後就可以進行各種操作了
複製代碼 代碼如下:
// Find all anchors, returns a array of element objects
$ret = $html->find('a');
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1);
// Find all with the id attribute
$ret = $html->find('div[id]');
// Find all which attribute id=foo
$ret = $html->find('div[id=foo]');

這裡可以使用各種css選取器,就像在jQuery中進行DOM操作一樣,非常方便。此外,還有兩個特殊的屬性可以得到文本和注釋的內容
複製代碼 代碼如下:
// Find all text blocks
$es = $html->find('text');
// Find all comment () blocks
$es = $html->find('comment');

當然,還是類似於jQuery,PHP Simple HTML DOM Parser也支援鏈式操作,以及各種訪問DOM元素的簡單方法
複製代碼 代碼如下:
// Example
echo $html->find("#div1", 0)->children(1)->children(1)->children(2)->id;
// or
echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes(2)->getAttribute('id');

http://www.bkjia.com/PHPjc/324200.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/324200.htmlTechArticle最近想用php寫一個爬蟲,就需要解析html,在sourceforge上找到一個項目叫做PHP Simple HTML DOM Parser,它可以以類似jQuery的方式通過css選取器來返回...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.