时间:2021-07-01 10:21:17 帮助过:28人阅读
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("TTT", $treeIndex); $tabEnd = "\r\n" . str_repeat("EEE", $treeIndex - 1); $i = 0; while ($childNode = $node->childNodes->item($i++)) { if ($childNode->nodeType == XML_TEXT_NODE) { if (preg_match('#^\s*$#', $childNode->nodeValue)) { $node->removeChild($childNode); $i--; continue; } $childNode->nodeValue = trim($childNode->nodeValue); } $node->insertBefore($node->ownerDocument->createTextNode($tabStart), $childNode); $i++; $this->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();
http://www.bkjia.com/PHPjc/1102843.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1102843.htmlTechArticlephp DOMDocument 递归 格式化缩进HTML文档, function format(\DOMNode $node , $treeIndex = 0 ){ // 不格式化的标签 if ( in_array ( $node -nodeName, array ("title", "p"...