HTML/XML查询(CSS 4或XPath)和处理(如jQuery)

v1.0.1 2022-01-05 22:37 UTC

This package is auto-updated.

Last update: 2024-09-06 04:26:59 UTC


README

此包基于querypath/querypatharthurkushman/query-path

此包受MIT许可证(COPYING-MIT.txt)许可。

概述

QueryPath是一个类似于jQuery的库,用于在PHP中处理XML和HTML文档。它现在包含通过HTML5-PHP项目对HTML5的支持。

为什么这个库被分叉和重写

  • 不兼容php 8.1

安装

composer require satisfactory-clips-archive/querypath

入门

假设您已通过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 [, $... ]])

要将QueryPath作为库添加到您的项目中,运行composer require satisfactory-clips-archive/querypath

<?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>