Reputation: 726
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?
Upvotes: 1
Views: 2231
Reputation: 18556
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
.
Upvotes: 2