使用sabberworm / PHP-CSS-Parser解析css文件 [英] parsing a css file with sabberworm/PHP-CSS-Parser

查看:400
本文介绍了使用sabberworm / PHP-CSS-Parser解析css文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用这个类来解析.css文件。
https://github.com/sabberworm/PHP-CSS-Parser
我认为这很容易,但这个类很复杂,我完全绿色的面向对象编程,所以我有一个问题。

I use this class to parse a .css file. https://github.com/sabberworm/PHP-CSS-Parser I thought it's easy but this class is complicated and I'm completly green in object oriented programing, so I have a problem.

(...)包括所有类文件等。

(...) including all class files etc.

$oParser = new CSSParser(file_get_contents('files/sample.css'));
$oDoc = $oParser->parse();
$selectors=$oDoc->getAllRuleSets();
$nazwy=$oDoc->getContents();

foreach($selectors as $selektor=> $val)
    {       
    $w=$val->getSelectors();            
    echo "<h3>$selektor</h3>";
    $tmp=$val->getRules();

        foreach($tmp as $nazwa => $attrib)
        {
        $wartosc= $attrib->getValue();
        echo "<br>$nazwa:$wartosc;";            
        }               
    }

此代码将输出如下

<h1>0</h1>
color:red;
margin:10px;


<h1>1</h1>
color:green;
margin:20px;

这几乎确定,但我想要选择器名称(例如div #someid),而不是当前css块的索引。

it's almost ok but I want selectors names (eg div #someid) instead of index of current css block.Have any idea how to get those?

推荐答案

使用 echo< h3>implode (','$ w)。< / h3>

原因如下: $ val 表示一个声明块,它是一个具有多个逗号分隔的选择器的规则集(键 $ selektor 只包含声明块的索引这对于大多数使用是完全任意的)。要获得选择器,使用 $ val-> gtSelectors()(你做的)。这将为您提供所有选择器的数组。

The reason is as follows: $val represents a declaration block which is a rule set with several comma-separated selectors (The key $selektor only contains the index of the declaration block which is completely arbitrary for most usages). To get the selectors, use $val->getSelectors() (which you did). This will get you an array of all selectors.

声明块:

h1, h2 { value: 1; }

将被解析为 CSSDeclarationBlock 对象与选择器数组['h1','h2']。要返回最初定义的选择器,请使用 implode

will thus be parsed into a CSSDeclarationBlock object with the selector array ['h1', 'h2']. To get back the selectors as they were originally defined, use implode.

这篇关于使用sabberworm / PHP-CSS-Parser解析css文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆