jeremiah-shaulov / joyquery-php
CSS选择器查询语言,支持XPath轴扩展,用于DOMDocument
v1.0.3
2020-07-26 00:57 UTC
Requires
- php: >=7.2
This package is auto-updated.
Last update: 2024-09-28 17:18:00 UTC
README
CSS选择器查询语言,支持XPath轴扩展。
安装
为您的应用程序创建一个目录,使用 cd 进入该目录,并执行
composer require jeremiah-shaulov/joyquery-php
示例
<?php require_once 'vendor/autoload.php'; use JoyQuery\JoyQuery; $doc = new DOMDocument; $doc->loadHTML('<div class=d hello=world><span>Hello</span></div>'); foreach (JoyQuery::evaluate('.d span:last-child', $doc) as $elem) { echo "Found: ", $doc->saveXml($elem->cloneNode(true)), "\n\n"; }
非标准特性
以下特性在标准中未找到,但已实现
E[foo!="bar"]- 一个E元素要么没有"foo"属性,要么有但值不等于"bar"E:not(s)- 一个不匹配选择器s的E元素。选择器s可以是任何简单或复杂的选择器(标准要求简单选择器)E:has(s)- 一个也匹配选择器s的E元素E:any(s1, s2, ...)- 一个也匹配给定选择器s1, s2, ...中的任何选择器的E元素E:input- 一个是INPUT、SELECT、TEXTAREA或BUTTON的E元素:from(n)- 当应用于简单选择器时,例如E.cls,只选择从匹配集中第n个开始的元素:limit(n)- 当应用于简单选择器时,例如E.cls,将匹配集限制为不超过n个元素axis::E- XPath类似的轴,见下文:php-func-name- 测试元素的PHP函数,见下文
轴
joyquery扩展CSS选择器语言,添加了类似XPath的轴。示例
td.clue parent::tr /* select TR, which is parent of TD.clue */ td.clue ancestor::table /* select all TABLES, which are ancestors of TD.clue */ .clue descendant-or-self::*:any(th, td)
以下轴可用
- self:
- child:
- descendant:
- descendant-or-self:
- parent:
- ancestor:
- ancestor-or-self:
- following-sibling:
- first-following-sibling:
- preceding-sibling:
- first-preceding-sibling:
扩展函数
您可以使用自定义函数扩展joyquery。
<?php require_once 'vendor/autoload.php'; use JoyQuery\JoyQuery; JoyQuery::$FUNCTIONS['has_text'] = function(DOMElement $node, $text) { return strpos($node->textContent, $text) !== false; }; $doc = new DOMDocument; $doc->loadHTML('<p>One</p> <p>Two</p> <p>Three</p>'); foreach (JoyQuery::evaluate('p:has-text("ee")', $doc) as $elem) { echo "Found: ", $doc->saveXml($elem->cloneNode(true)), "\n\n"; }