views:

51

answers:

2

Hi,

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!

+2  A: 

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;

?>
Josh Stodola
First: thanks a lot! That is exactly what I was looking for! So far it is not working with the HTML example I gave in the question, but I guess I should wrap a HTML header around it so it would be XML compatible..
Tom
@Tom I updated the answer, it should be a complete solution now
Josh Stodola
@Tom And this is untested, and I don't know PHP!
Josh Stodola
+1  A: 

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

Hubert Perron
OMG! I'd never though it'd be that simple! I mean: all I did was new SimpleXMLElement($source) and it returned me a complete array with everything I needed! "We have a SITUATION!" Thx for this!
Tom