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;";
}
}
this code will output something like this
<h1>0</h1>
color:red;
margin:10px;
<h1>1</h1>
color:green;
margin:20px;
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?
Use
echo "<h3>".implode(', ' $w)."</h3>".The reason is as follows:
$valrepresents a declaration block which is a rule set with several comma-separated selectors (The key$selektoronly 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:
will thus be parsed into a
CSSDeclarationBlockobject with the selector array [‘h1’, ‘h2’]. To get back the selectors as they were originally defined, useimplode.