Rumah > pembangunan bahagian belakang > tutorial php > php DOMDocument 递归 格式化缩进HTML文档

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Lepaskan: 2016-07-29 09:02:03
asal
1160 orang telah melayarinya

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> = '<meta charset="utf-8"><title></title>'<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();
Salin selepas log masuk

以上就介绍了php DOMDocument 递归 格式化缩进HTML文档,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Isu terkini
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan