使用PHP-CSS-PARSE解析css并生成文件

时间:2014-04-23 06:38:48

标签: php css parsing

我正在尝试使用Raphael Schweikert的lib解析CSS文件Sabberworm\PHP-CSS-PARSE

但我被对象操纵阻止了。我要做的是转换这个css文件:

.header {
  background: #000;
}

.footer, .wrapper {
  background: #ebebeb;
}

以PHP / JSON格式:

 '.header'  => "background: #000;",
 '.footer'  => "background: #ebebeb;",
 '.wrapper' => "background: #ebebeb;"

我做了什么:

<?php

require 'vendor/autoload.php';
$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('style.css'));
$oCssDocument = $oCssParser->parse();
$selectors=$oCssDocument->getAllRuleSets();
...

但如何循环?像我这样的neewbe对象的结构并不容易......

2 个答案:

答案 0 :(得分:0)

(这应该是一个评论,但使用代码可以更好阅读。)

我不熟悉PHP-CSS-PARSE,但我有一个观察:我会假设

.footer .wrapper {
  background: #ebebeb;
}

将成为'.footer .wrapper' => "background: #ebebeb;"

如果你想要

'.footer'  => "background: #ebebeb;",
'.wrapper' => "background: #ebebeb;"

然后CSS必须是

.footer, .wrapper {
  background: #ebebeb;
}

(注意逗号)或必须有单独的规则。

答案 1 :(得分:0)

我昨天很懒...

<?php

require 'vendor/autoload.php';

$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('style.css'));
$oCssDocument = $oCssParser->parse();

foreach ($oCssDocument->getAllRuleSets() as $oRuleSet) {

    $sSelector = $oRuleSet->getSelectors();
    foreach ($sSelector as $currentSelector) {
            $sSelector = $currentSelector->getSelector();
            echo "\r\n\"$sSelector\" = \"";
            foreach( $oRuleSet->getRules() as $sRules) {
                echo "$sRules ";
            }
            echo "\"";
    }
}

呈现

".header" = "background: #000; "
".footer" = "background: #ebebeb; "
".wrapper" = "background: #ebebeb; "