php解析html类库simple_html_dom

て烟熏妆下的殇ゞ 提交于 2020-03-18 06:12:52

本文介绍simple_html_dom,就是用来处理网页,可以写爬虫抓取信息;

背景:在项目中获得一个很长的html标签的长字符串,需要解析到里面所有的<img>标签的的src地址;

用正则匹配来做比较麻烦,在朋友的推荐下使用simple_html_dom非常方便,

这个组件不光可以解析字符串,也可以直接传入文件地址和网页url;

下面举例:

<?php
$content = '';//html内容

//
header("Content-type: text/html; charset=utf-8");
include('simple_html_dom.php');
$html = new simple_html_dom();
$html->load($content);
$img = $html->find('img');
foreach ($img as $value) { 
    $src[] = $value->getAttribute('data-src');  //获取自定义属性要用getAttribute,否则无法取到
}
echo "<pre>";
var_dump($src);
echo "</pre>";

1.首先要引入simple_html_dom库。git地址:https://github.com/samacs/simple_html_dom。

2.参照git里面的例子使用

3.中文文档:http://microphp.us/plugins/public/microphp_res/simple_html_dom/manual.htm#section_create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!