/** * indent a HTML string properly * * @param string $html * @param string $indent optional * @return string */ function indentHTML($html, $indent = " ", $noTagsInCode = false) { $parser = new parseHTML(); $parser->noTagsInCode = $noTagsInCode; $parser->html = $html; $html = ''; $last = true; # last tag was block elem $indent_a = array(); while ($parser->nextNode()) { if ($parser->nodeType == 'tag') { $parser->normalizeNode(); } if ($parser->nodeType == 'tag' && $parser->isBlockElement) { $isPreOrCode = in_array($parser->tagName, array('code', 'pre')); if (!$parser->keepWhitespace && !$last && !$isPreOrCode) { $html = rtrim($html) . "\n"; } if ($parser->isStartTag) { $html .= implode($indent_a); if (!$parser->isEmptyTag) { array_push($indent_a, $indent); } } else { array_pop($indent_a); if (!$isPreOrCode) { $html .= implode($indent_a); } } $html .= $parser->node; if (!$parser->keepWhitespace && !($isPreOrCode && $parser->isStartTag)) { $html .= "\n"; } $last = true; } else { if ($parser->nodeType == 'tag' && $parser->tagName == 'br') { $html .= $parser->node . "\n"; $last = true; continue; } elseif ($last && !$parser->keepWhitespace) { $html .= implode($indent_a); $parser->node = ltrim($parser->node); } $html .= $parser->node; if (in_array($parser->nodeType, array('comment', 'pi', 'doctype'))) { $html .= "\n"; } else { $last = false; } } } return $html; }