PHP Simple HTML DOM Parser – 用PHP轻松解析HTML DOM
这个玩意,用来采集挺好的。别的就不废话了。
项目地址:http://simplehtmldom.sourceforge.net/
简介
- 使用PHP5实现的HTML DOM解析器。让你能够使用PHP5轻松操纵HTML DOM。
- 支持PHP5及以上版本。
- 像jQuery一样使用选择器获取HTML标签。
- 一行代码获取HTML中的内容。
快速入门
1、如何获取HTML节点?
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
2、如何修改HTML节点?
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
3、从HTML中获取内容
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;
echo file_get_html('http://www.google.com/')->plaintext;