代码之家  ›  专栏  ›  技术社区  ›  Tommy B.

用PHP解析HTML从ids和classes属性返回CSS规则

  •  2
  • Tommy B.  · 技术社区  · 15 年前

    我不想写下很多CSS规则,然后在其中输入我的样式,所以我想开发一个小的php脚本来解析我传递给它的HTML,然后返回空的CSS规则。

    我决定使用PHP的DomDocument。

    问题是:我怎样才能循环浏览整个结构?(例如,我看到DomDocument只有getElementByTag或getElementById,没有getFirstElement)

    我只想获取给定HTML代码块中的I d和类,我会传递如下内容:

    <div id="testId">
        <div class="testClass">
            <span class="message error">hello world</span>
        </div>
    </div>
    

    我只想知道如何循环遍历每个节点?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Hubert Perron    15 年前

    PHP的SimpleXML扩展可能会帮助您。它可以很好地在HTML树中导航。

    http://www.php.net/manual/en/simplexml.examples-basic.php

        2
  •  3
  •   Josh Stodola    15 年前

    您可以将星号(*)传递给 getElementsByTagName 获取所有标签,然后遍历它们。。。

    <?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;
    
    ?>