首頁 > 後端開發 > php教程 > php DOMDocument 遞迴 格式化縮排HTML文檔

php DOMDocument 遞迴 格式化縮排HTML文檔

WBOY
發布: 2016-07-29 09:02:03
原創
1152 人瀏覽過

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>("   ", <span>$treeIndex</span><span>);
        </span><span>$tabEnd</span> = "\r\n" . <span>str_repeat</span>("   ", <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>//</span><span>去除空的text node</span><span>if</span> (<span>$childNode</span>->nodeType == XML_TEXT_NODE and <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>$node</span>->insertBefore(<span>$node</span>->ownerDocument->createTextNode(<span>$tabStart</span>), <span>$childNode</span><span>);
            </span><span>$i</span>++<span>;
            format(</span><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><span>);
format(</span><span>$doc</span>-><span>documentElement);
</span><span>echo</span><span>$doc</span>->saveHTML();
登入後複製

以上就介紹了php DOMDocument 遞歸 格式化縮排HTML文檔,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板