我想构建类似于CSS Generator的东西。这是我到目前为止所做的工作:
<?php
header('Content-type: text/plain');
$source = '<body class="theme">
<div class="header">
<h1><a href="#">Welcome</a></h1>
</div>
<div class="content">
<div class="sidebar">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
</div>
<div class="main">
<h2>Main Heading</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>
<div class="footer">
<p>Copyright © 2012 Me!</p>
</div>
</body>';
$html = new DOMDocument;
$html->loadHTML($source);
$nodes = $html->getElementsByTagName("*");
$css = "";
for ($i = 0; $i < $nodes->length; $i++) {
$node = $nodes->item($i);
if(!$node->hasAttribute("class") && !$node->hasAttribute("id"))
$css = $css . str_replace(array("/"), array(" "), $node->getNodePath()) . " {}\n";
if ($node->hasAttribute("class")) {
$css = $css . $node->nodeName . "." . $node->getAttribute("class") . " {}\n";
} elseif ($node->hasAttribute("id")) {
$css = $css . "#" . $node->getAttribute("id") . " {}\n";
}
}
echo $css;
?>
我得到的输出不是正确的。所需的输出是:
body.theme div.header {}
body.theme div.header h1 {}
body.theme div.header h1 a {}
body.theme div.content {}
body.theme div.content div.sidebar {}
body.theme div.content div.sidebar ul {}
body.theme div.content div.sidebar ul li {}
body.theme div.content div.sidebar ul li a {}
body.theme div.content div.main {}
body.theme div.content div.main h2 {}
body.theme div.content div.main p {}
body.theme div.footer {}
body.theme div.footer p {}
但现在我得到的是:
html {}
body.theme {}
div.header {}
html body div[1] h1 {}
html body div[1] h1 a {}
div.content {}
div.sidebar {}
html body div[2] div[1] ul {}
html body div[2] div[1] ul li[1] {}
html body div[2] div[1] ul li[1] a {}
html body div[2] div[1] ul li[2] {}
html body div[2] div[1] ul li[2] a {}
html body div[2] div[1] ul li[3] {}
html body div[2] div[1] ul li[3] a {}
html body div[2] div[1] ul li[4] {}
html body div[2] div[1] ul li[4] a {}
html body div[2] div[1] ul li[5] {}
html body div[2] div[1] ul li[5] a {}
div.main {}
html body div[2] div[2] h2 {}
html body div[2] div[2] p {}
div.footer {}
html body div[3] p {}
我试图尽可能多地操纵,但无法变得更好。你们能帮帮我吗?