时间:2021-07-01 10:21:17 帮助过:13人阅读
function format(\DOMNode $node, $treeIndex = 0) { //不格式化的标签if (in_array($node->nodeName, array("title", "p", "span"))) return; if ($node->hasChildNodes()) { $treeIndex++; $tabStart = "\r\n" . str_repeat(" ", $treeIndex); $tabEnd = "\r\n" . str_repeat(" ", $treeIndex - 1); $i = 0; while ($childNode = $node->childNodes->item($i++)) { //去除空的text nodeif ($childNode->nodeType == XML_TEXT_NODE and preg_match('#^\s*$#', $childNode->nodeValue)) { $node->removeChild($childNode); $i--; continue; } $node->insertBefore($node->ownerDocument->createTextNode($tabStart), $childNode); $i++; format($childNode, $treeIndex); }; $node->appendChild($node->ownerDocument->createTextNode($tabEnd)); } } $html = ''; $doc = new \DOMDocument(); //$doc->formatOutput = true; //不知道是不是我的理解问题,这个选项格式化出来的并不完美$doc->loadHTML($html); format($doc->documentElement); echo$doc->saveHTML();
以上就介绍了php DOMDocument 递归 格式化缩进HTML文档,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。