使用php的tidy解析html

以前解析html都是使用正则表达式,但是用起来比较麻烦。现在开始使用php的tidy库。

示例如下: 摘自:http://us3.php.net/tidy.root

<?php
 
$html = <<< HTML
 
paragraph
 
HTML;
 
$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);
 
function dump_nodes($node, $indent) {
 
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";
 
            dump_nodes($child, $indent+1);
        }
    }
}
?>

要注意的一点是,对于GBK编码的HTML需要先转换编码为UTF8的,然后使用

$tidy = new tidy;
$tidy ->parseString($html, array(), 'utf8');

来解析。

====后续分割线===

最近又使用一种新的方法来解析html,当然还是用php。

使用一个叫做PHP Simple HTML DOM Parser的类。感谢某同学的帮助。

英文链接地址:http://simplehtmldom.sourceforge.net/

中文链接地址:http://phpdom.comsing.com/

这个类使用起来非常方便,单就解析html这一点来说,比tidy好用。而且文档齐全,简单易懂。

示例如下:

                $html = new simple_html_dom();
		$html->load($content);
 
		$result = array();
 
		foreach($html->find('a') as $a){
			$img = $a->find('img', 0);
			if(isset($a->href) && isset($img->src)){
				$result[] =  array(
							'href' => $a->href,
							'src'  => $img->src,
				);
 
			}
		}

发表评论