soloproyectos-php/css-parser

一个用于管理CSS表达式的库。此库是 SoloProyectos PHP API 的一部分。

此软件包的官方仓库似乎已消失,因此该软件包已被冻结。

安装: 739

依赖者: 1

建议者: 0

安全: 0

星标: 0

关注者: 0

分支: 0

类型:php-library

1.1.1 2018-01-29 06:03 UTC

This package is not auto-updated.

Last update: 2024-05-11 14:19:36 UTC


README

一个用于评估CSS表达式的库。

此库可用于使用CSS选择器从DOM文档中选择元素。

安装

只需执行以下命令

composer require soloproyectos-php/css-parser

示例

您可以从不同的来源创建CssParser的实例

// Loads a DOMDocument
$doc = new DOMDocument("1.0", "UTF-8");
$doc->loadXML('<root><item id="101" /><item id="102" /></root>');
$selector = new CssParser($doc);

// Loads a DOMElement
$doc = new DOMDocument("1.0", "UTF-8");
$doc->loadXML('<root><item id="101" /><item id="102" /></root>);
$root = $doc->documentElement;
$selector = new CssParser($root);

// Loads a file
$selector = new CssParser('/path/to/my/document.xml');

// Loads an URL
$selector = new CssParser('http://www.my-site.com/document.xml');

选择第一个和奇数元素

$doc = new DOMDocument("1.0", "UTF-8");
$doc->loadXML(
    '<root><item id="101" /><item id="102" /></root>'
);
$selector = new CssSelector($doc);

// selects the first and the odd elements and prints them
$items = $selector->query('item:odd, item:first-child');
foreach ($items as $item) {
    echo $doc->saveXML($item) . "\n";
}

此库支持多种CSS伪筛选器,如:odd:evenfirst-child等。但您可以创建自定义的。以下示例声明了一个fibonacci伪筛选器

// is the position of the node a Fibonacci number?
$css->registerPseudoFilter("fibonacci", function ($node, $input, $position, $items) {
    $isFibonacci = false;
    if ($position > 0) {
        $n = sqrt(5 * pow($position, 2) + 4);
        $isFibonacci = $n - floor($n) == 0;
        if (!$isFibonacci) {
            $n = sqrt(5 * pow($position, 2) - 4);
            $isFibonacci = $n - floor($n) == 0;
        }
    }
    return $isFibonacci;
});

// selects only `fibonacci` nodes
$items = $selector->query('item:fibonacci');

您可以在源代码本身中找到更多示例
src/css/parser/CssParser.php

祝您享受!