PHP使用simple_html_dom解析HTML示例
本实例详细阐述了在PHP环境中运用simple_html_dom技术解析HTML文档的具体方案,旨在为读者提供具有参考价值的实践指南。
近期完成了两项爬虫程序的编写工作,分别基于Python和PHP语言实现。从实际开发体验来看,这两种语言的实现路径均十分便捷高效。
接下来重点介绍如何利用simple_html_dom这一开源组件来完成HTML代码的解析任务。
第一步:获取simple_html_dom资源。
访问SourceForge项目页面:http://sourceforge.net/projects/simplehtmldom/files/ 进行下载。
亦可通过本站提供的链接直接下载该组件。
第二步:查看具体的用法示例。
<?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 . '
';
// find all image
foreach($html->find('img') as $e)
echo $e->src . '
';
// find all image with full tag
foreach($html->find('img') as $e)
echo $e->outertext . '
';
// find all div tags with id=gbar
foreach($html->find('div#gbar') as $e)
echo $e->innertext . '
';
// find all span tags with class=gb1
foreach($html->find('span.gb1') as $e)
echo $e->outertext . '
';
// find all td tags with attribite align=center
foreach($html->find('td[align=center]') as $e)
echo $e->innertext . '
';
// extract text from table
echo $html->find('td[align="center"]', 1)->plaintext.'
<hr>';
// extract text from HTML
echo $html->plaintext;
?>
期望上述内容能对各位PHP程序员的开发工作带来实质性的帮助。