[imangazaliev/didom]一个简单又快速的DOM操作库

2023-04-08 奥古斯宏

DiDOM是一个功能齐全、易于使用和高性能的解析器和操作库,可以帮助PHP开发者更加高效地处理HTML文档。

为了更好地了解这个项目,我们先来看看下面的介绍。

安装

你可以使用composer来安装DiDOM,只需要在你的项目目录下执行下面的命令:

composer require imangazaliev/di-dom

构建DOM树

使用DiDOM,您可以轻松地将HTML或XML代码转换为DOM树。支持各种形式的初始化和调用,下面是一个示例:

// 初始化加载
$document = new Document($html);

// 本地文件
$document = new Document('page.html', true);

// 网络文件
$document = new Document('http://www.example.com/', true);

// 或者使用方法加载
$document = new Document();

$document->loadHtml($html);

$document->loadHtmlFile('page.html');

$document->loadHtmlFile('http://www.example.com/');

查询元素

DIDOM支持丰富且方便的查询方法,您可以轻松地查询DOM树中的元素。最基本的有CSS选择器和XPath方法:


// CSS 选择器
$posts = $document->find('.post');

// XPath
$posts = $document->find("//div[contains(@class, 'post')]", Query::TYPE_XPATH);

几乎支持页面中常见的所有CSS选择器:

版权声明:本文由phpreturn.com(PHP武器库官网)原创和首发,所有权利归phpreturn(PHP武器库)所有,本站允许任何形式的转载/引用文章,但必须同时注明出处。

// 所有A标签
$document->find('a');

// ID为 "foo" 且 class 为 "bar" 
$document->find('#foo.bar');

// 包含属性"name"
$document->find('[name]');
// 也可以写为
$document->find('*[name]');

// input的name为"foo"
$document->find('input[name=foo]');
$document->find('input[name=\'bar\']');
$document->find('input[name="baz"]');

// 任何以data开头且value为foo的
$document->find('*[^data-=foo]');

// 所有https开头的a标签
$document->find('a[href^=https]');

// 所有扩展名为png的
$document->find('img[src$=png]');

// 所有链接匹配"example.com"
$document->find('a[href*=example.com]');

// 类名是"foo"的a标签的text
$document->find('a.foo::text');

// 找对应的href和title
$document->find('a.bar::attr(href|title)');

丰富的链式调用

DiDOM还有许多其他有用的特性和功能,例如:

  • 使用CSS选择器查询元素
  • 获取和设置元素属性
  • 获取和设置元素文本
  • 删除元素
  • 将DOM树转换为HTML或XML代码
  • 将HTML或XML代码格式化为易于阅读的形式

总结

至此,我们介绍了DiDOM解析器的主要功能和用法。DiDOM不仅功能强大,而且易于使用,是一个非常有价值的工具。如果您需要解析和操作HTML或XML文档,不妨试试DiDOM。


最近浏览
IP用户:66.249.*.*
4 小时前 Googlebot
IP用户:42.202.*.*
1 天前 Go-http-client
IP用户:60.188.*.*
1 天前 Generic Bot
IP用户:34.64.*.*
2 天前 Googlebot
IP用户:34.64.*.*
3 天前 Googlebot
IP用户:74.125.*.*
3 天前 Googlebot
IP用户:42.202.*.*
4 天前 Go-http-client
IP用户:60.188.*.*
4 天前 Generic Bot
IP用户:34.64.*.*
7 天前 Googlebot
IP用户:66.249.*.*
7 天前 Googlebot
IP用户:34.64.*.*
8 天前 Googlebot
IP用户:54.36.*.*
9 天前 aHrefs Bot
累计浏览次数:827
评论
点击登录
phpreturn,PHP武器库,专注PHP领域的项目和资讯,收录和介绍PHP相关项目。
最近浏览 点击登录
IP用户:123.149.*.*
IP用户:3.133.*.*
IP用户:223.93.*.*
累计浏览次数:102667
一周浏览次数:3373
今日浏览次数:479

本站所有权利归 phpreturn.com 所有

举报/反馈/投稿邮箱:phpreturn@ulthon.com

鲁ICP备19027671号-2