庆云php

庆云php

PHP使用Simple_HTML_DOM遍历树、过滤及保留指定属性

PHP 0

2023年11月20日 每日一猜答案: 答案:ABC
每日一猜答案分析:

    array( 'src', 'alt' , 'title' , 'width' , 'height'  ),
            'a' => array( 'href', 'title', 'target'),
        );

  
        $html = new simple_html_dom();
// 从字符串中加载
      $html->load_file('http://www.baidu.com');


   
            global $HtmlUtil;
            $HtmlUtil = new HtmlUtil;
            $html = $HtmlUtil->clear_html_attribute( $html, $allow, $exceptions );
            $html11='';
            if(!empty($html)){
               // 获得清理后的文本
                $html11=$html->root->innertext();
                $html->clear();
            }
 }



';
// return;
// if($levelval==200){//递归调用200次时,就直接终止取空并返回
// $html_dom->outertext = '';
// return;
// }

$ww=$html_dom->outertext;
$ww1=$html_dom->innertext;

if(empty(trim($ww1))){
$html_dom->outertext = '';
return;
}
if($html_dom->tag=='a'){//清除所有超链接
$pos = strpos($html_dom->innertext, 'http');
if($pos===false){
$html_dom->outertext = $html_dom->innertext;
}else{
$html_dom->outertext = '';
}

}elseif($html_dom->tag=='img'){//清除所有图片
$html_dom->outertext = '';
}else{//清除所有指定的属性
$this->clear_attribute( $html_dom, $allow, $exceptions );
foreach( $html_dom->find('*') as $html_child_dom )
{
$this->clear_child_html_attribute( $html_child_dom, $allow, $exceptions,$levelval );
$this->clear_attribute( $html_child_dom, $allow, $exceptions );
}
}

}

public function clear_attribute( $html_dom, $allow = array(), $exceptions = array() )
{
//遍历属性
$attrs = $html_dom->getAllAttributes();

if( count( $attrs ) > 0 )
{
//遍历属性,进行处理
foreach( $attrs as $attr_key => $attr_value )
{
//如果是例外的,则不管
$exceptions_attrs = $exceptions[ $html_dom->tag ]??'';
if( is_array( $exceptions_attrs ) && in_array( $attr_key , $exceptions_attrs ) ){ continue; }

//如果不再允许列表中,则删除
if( is_array( $allow ) && in_array( $attr_key , $allow ) ){ continue; }
$html_dom->removeAttribute( $attr_key );
}
}

}

public function clear_html_attribute( $html_str, $allow = array(), $exceptions= array() )
{

$html = str_get_html( $html_str );
if(!empty($html)){
foreach( $html->find( "*" ) as $html_dom )
{
//处理所有节点的属性
$this->clear_child_html_attribute( $html_dom, $allow, $exceptions );
}
}
return $html;
}

function clear_html_post( $post_id )
{
if ( ! wp_is_post_revision( $post_id ) ){

remove_action('save_post', array( $this, 'clear_html_post') );

$my_post = get_post( $post_id );
$my_post->post_content = $this->clear_html( $my_post->post_content );

wp_update_post( $my_post );

add_action('save_post', array( $this, 'clear_html_post') );
}
}
}

      更多完整的 hp解析html类库simple_html_dom(详细介绍)_php技巧 下载地址:https://github.com/samacs/simple_html_dom 解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。 开始使用 一直以来使用php解析html文档树都是一个难题。Simple HTML DOM parser 帮我们很好地解决了这个问题。可以通过这个php类来解析html文档,对其中的html元素进行操作 (PHP5+以上版本) 上传类文件以后,有三种方式调用这个类: 从url中加载html文档 从字符串中加载html文档 从文件中加载html文档 复制代码代码如下: // 新建一个Dom实例 $html = new simple_html_dom(); // 从url中加载 $html->load_file(‘http://www.75271.com’;); // 从字符串中加载 $html->load(‘ 从字符串中加载html文档演示’); //从文件中加载 $html->load_file(‘path/file/test.html’); ?> 如果从字符串加载html文档,需要先从网络上下载。建议使用cURL来抓取html文档并加载DOM中。 查找html元素 可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例: 复制代码代码如下: //查找html文档中的超链接元素 $a = $html->find(‘a’); //查找文档中第(N)个超链接,如果没有找到则返回空数组. $a = $html->find(‘a’, 0); // 查找id为main的div元素 $main = $html->find(‘div[id=main]’,0); // 查找所有包含有id属性的div元素 $divs = $html->find(‘div[id]’); // 查找所有包含有id属性的元素 $divs = $html->find(‘[id]’); ?> 还可以使用类似jQuery的选择器来查找定位元素: 复制代码代码如下: // 查找id=’#container’的元素 $ret = $html->find(‘#container’); // 找到所有class=foo的元素 $ret = $html->find(‘.foo’); // 查找多个html标签 $ret = $html->find(‘a, img’); // 还可以这样用 $ret = $html->find(‘a[title], img[title]’); ?> 解析器支持对子元素的查找 复制代码代码如下: // 查找 ul列表中所有的li项 $ret = $html->find(‘ul li’); //查找 ul 列表指定class=selected的li项 $ret = $html->find(‘ul li.selected’); ?> 如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素 复制代码代码如下: // 返回父元素 $e->parent; // 返回子元素数组 $e->children; // 通过索引号返回指定子元素 $e->children(0); // 返回第一个资源速 $e->first_child (); // 返回最后一个子元素 $e->last _child (); // 返回上一个相邻元素 $e->prev_sibling (); //返回下一个相邻元素 $e->next_sibling (); ?> 元素属性操作 使用简单的正则表达式来操作属性选择器。 [attribute] – 选择包含某属性的html元素 [attribute=value] – 选择所有指定值属性的html元素 [attribute!=value]- 选择所有非指定值属性的html元素 [attribute^=value] -选择所有指定值开头属性的html元素 [attribute$=value] 选择所有指定值结尾属性的html元素 [attribute*=value] -选择所有包含指定值属性的html元素 在解析器中调用元素属性 在DOM中元素属性也是对象: 复制代码代码如下: // 本例中将$a的锚链接值赋给$link变量 $link = $a->href; ?> 或者: 复制代码代码如下: $link = $html->find(‘a’,0)->href; ?> 每个对象都有4个基本对象属性: tag – 返回html标签名 innertext – 返回innerHTML outertext – 返回outerHTML plaintext – 返回html标签中的文本 在解析器中编辑元素 编辑元素属性的用法和调用它们是类似的: 复制代码代码如下: //给$a的锚链接赋新值 $a->href = ‘http://www.75271.com’;; // 删除锚链接 $a->href = null; // 检测是否存在锚链接 if(isset($a->href)) { //代码 } ?> 解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用: 复制代码代码如下: // 封装元素 $e->outertext = ‘
‘ . $e->outertext . ‘ 
‘;// 删除元素  $e->outertext = ”; // 添加元素 $e->outertext = $e->outertext . ‘
foo 
‘;// 插入元素  $e->outertext = ‘
foo 
‘ . $e->outertext;?>  保存修改后的html DOM文档也非常简单: 复制代码代码如下: $doc = $html; // 输出 echo $doc; ?> 如何避免解析器消耗过多内存 在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^ 复制代码代码如下: $html->clear(); ?>