1

このクラスを使用して .css ファイルを解析します。 https://github.com/sabberworm/PHP-CSS-Parser 簡単だと思っていましたが、このクラスは複雑で、オブジェクト指向プログラミングに完全に慣れているので、問題があります。

(...)すべてのクラスファイルなどを含む

$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;

ほとんど問題ありませんが、現在の css ブロックのインデックスではなく、セレクター名 (例: div #someid) が必要です。それらを取得する方法はありますか?

4

1 に答える 1

2

Use echo "<h3>".implode(', ' $w)."</h3>".

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.

The declaration block:

h1, h2 { value: 1; }

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.

于 2012-06-21T09:53:17.380 に答える