首页 >后端开发 >php教程 >php DOMDocument 递归 格式化缩进HTML文档,_PHP教程

php DOMDocument 递归 格式化缩进HTML文档,_PHP教程

WBOY
WBOY原创
2016-07-12 08:58:361166浏览

php DOMDocument 递归 格式化缩进HTML文档,

<span>function</span> format(\DOMNode <span>$node</span>, <span>$treeIndex</span> = 0<span>)
{
    </span><span>//</span><span>不格式化的标签</span>
    <span>if</span> (<span>in_array</span>(<span>$node</span>->nodeName, <span>array</span>("title", "p", "span"<span>)))
        </span><span>return</span><span>;
    </span><span>if</span> (<span>$node</span>-><span>hasChildNodes()) {
        </span><span>$treeIndex</span>++<span>;
        </span><span>$tabStart</span> = "\r\n" . <span>str_repeat</span>("TTT", <span>$treeIndex</span><span>);
        </span><span>$tabEnd</span> = "\r\n" . <span>str_repeat</span>("EEE", <span>$treeIndex</span> - 1<span>);
        </span><span>$i</span> = 0<span>;
        </span><span>while</span> (<span>$childNode</span> = <span>$node</span>->childNodes->item(<span>$i</span>++<span>)) {
            </span><span>if</span> (<span>$childNode</span>->nodeType ==<span> XML_TEXT_NODE) {
                </span><span>if</span> (<span>preg_match</span>('#^\s*$#', <span>$childNode</span>-><span>nodeValue)) {
                    </span><span>$node</span>->removeChild(<span>$childNode</span><span>);
                    </span><span>$i</span>--<span>;
                    </span><span>continue</span><span>;
                }
                </span><span>$childNode</span>->nodeValue = <span>trim</span>(<span>$childNode</span>-><span>nodeValue);
            }
            </span><span>$node</span>->insertBefore(<span>$node</span>->ownerDocument->createTextNode(<span>$tabStart</span>), <span>$childNode</span><span>);
            </span><span>$i</span>++<span>;
            </span><span>$this</span>->format(<span>$childNode</span>, <span>$treeIndex</span><span>);
        };
        </span><span>$node</span>->appendChild(<span>$node</span>->ownerDocument->createTextNode(<span>$tabEnd</span><span>));
    }
}

</span><span>$html</span> = '<!DOCTYPE html><html><head><meta charset="utf-8"><title></title></head><body></body></html>'<span>;
</span><span>$doc</span> = <span>new</span><span> \DOMDocument(); 
</span><span>//</span><span>$doc->formatOutput = true; //不知道是不是我的理解问题,这个选项格式化出来的并不完美</span>
<span>$doc</span>->loadHTML(<span>$html</span>); format(<span>$doc</span>-><span>documentElement);
</span><span>echo</span> <span>$doc</span>->saveHTML();

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1102843.htmlTechArticlephp DOMDocument 递归 格式化缩进HTML文档, function format(\DOMNode $node , $treeIndex = 0 ){ // 不格式化的标签 if ( in_array ( $node -nodeName, array ("title", "p"...
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn