arthurkushman / query-path
HTML/XML 查询(CSS 4 或 XPath)和处理(如 jQuery)
3.1.4
2022-03-28 14:28 UTC
Requires
- php: >=7.1
- masterminds/html5: 2.*
Requires (Dev)
- fzaninotto/faker: ^1.8
- mockery/mockery: ^1.1
- phpunit/phpunit: ^7.2
This package is auto-updated.
Last update: 2024-09-12 17:02:23 UTC
README
概览
QueryPath 是一个类似 jQuery 的库,用于在 PHP 中操作 XML 和 HTML 文档。现在它包含了通过 HTML5-PHP 项目 对 HTML5 的支持。
为什么这个库被分叉和重新编写
- 遗留代码(仓库已闲置超过 3 年)不允许支持 PHP>=7.1 的新特性
- 大量未使用的代码,如:未使用的参数、未使用的局部变量等
- 大量不必要的流程结构
- 开发时丢弃了 DRY/KISS/SOLID 规则
- 一些小错误和不稳定的函数
安装
composer require arthurkushman/query-path
开始使用
假设您已成功通过 Composer 安装了 QueryPath,您可以像这样解析文档
// HTML5 (new)
$qp = html5qp("path/to/file.html");
// Legacy HTML via libxml
$qp = htmlqp("path/to/file.html");
// XML or XHTML
$qp = qp("path/to/file.html");
// All of the above can take string markup instead of a file name:
$qp = qp("<?xml version='1.0'?><hello><world/></hello>")
但真正的力量来自于链式操作。请查看下面的示例。
使用示例
假设我们有一个这样的文档
<?xml version="1.0"?> <table> <tr id="row1"> <td>one</td><td>two</td><td>three</td> </tr> <tr id="row2"> <td>four</td><td>five</td><td>six</td> </tr> </table>
假设上述内容存储在变量 $xml
中。现在我们可以这样使用 QueryPath
<?php // Add the attribute "foo=bar" to every "td" element. qp($xml, 'td')->attr('foo', 'bar'); // Print the contents of the third TD in the second row: echo qp($xml, '#row2>td:nth(3)')->text(); // Append another row to the XML and then write the // result to standard output: qp($xml, 'tr:last')->after('<tr><td/><td/><td/></tr>')->writeXML(); ?>
(此示例在 examples/at-a-glance.php
中。)
拥有超过 60 个函数和强大的链式操作支持,您可以使用 QueryPath 完成复杂的 XML 和 HTML 处理。
从那里,您主要想使用的函数是 qp()
(QueryPath::with()
的别名)和 htmlqp()
(QueryPath::withHTML()
的别名)。
QueryPath 格式扩展
format()
\QueryPath\DOMQuery format(callable $callback [, mixed $args [, $... ]])
快速示例
<?php QueryPath::enable(Format::class); $qp = qp('<?xml version="1.0"?><root><div>_apple_</div><div>_orange_</div></root>'); $qp->find('div') ->format('strtoupper') ->format('trim', '_') ->format(function ($text) { return '*' . $text . '*'; }); $qp->writeXML();
输出
<?xml version="1.0"?> <root> <div>*APPLE*</div> <div>*ORANGE*</div> </root>
formatAttr()
\QueryPath\DOMQuery formatAttr(string $name, callable $callback [, mixed $args [, $... ]])
快速示例
<?php QueryPath::enable(Format::class); $qp = qp('<?xml version="1.0"?><root>' . '<item label="_apple_" total="12,345,678" />' . '<item label="_orange_" total="987,654,321" />' . '</root>'); $qp->find('item') ->formatAttr('label', 'trim', '_') ->formatAttr('total', 'str_replace[2]', ',', ''); $qp->find('item')->formatAttr('label', function ($value) { return ucfirst(strtolower($value)); }); $qp->writeXML();
输出
<?xml version="1.0"?> <root> <item label="Apple" total="12345678"/> <item label="Orange" total="987654321"/> </root>