Parsing HTML to return CSS rules from ids and classes attributes with PHP
I hate to have to write down a lot of CSS rules and then enter my styles in it, so I'd like to develop a tiny php script that would parse the HTML I'd pass to it and then return empty CSS rules.
I decided to use PHP's DomDocument.
The question is: How could I loop through the whole structure? (I saw that for example DomDocument only has getElementByTag or getElementById and no getFirstElement for example)
I only want to get the ids and the 开发者_运维问答classes in a given block of HTML code, I'd pass things like:
<div id="testId">
<div class="testClass">
<span class="message error">hello world</span>
</div>
</div>
I only want to know how could I loop through every node?
Thanks!
You can pass an asterisk (*) to getElementsByTagName
to get all tags and then loop through them...
<?php
$nodes = $xml->getElementsByTagName("*");
$css = "";
for ($i = 0; $i < $nodes->length; $i ++)
{
$node = $nodes->item($i);
if ($node->hasAttribute("class")) {
$css = $css . "." . $node->getAttribute("class") . " { }\n";
} elseif ($node->hasAttribute("id")) {
$css = $css . "#" . $node->getAttribute("id") . " { }\n";
}
}
echo $css;
?>
The SimpleXML extension for PHP may help you. It work perfectly to navigate through HTML tree.
http://www.php.net/manual/en/simplexml.examples-basic.php
精彩评论