结果:
<!DOCTYPE html>
<html>
<head>
<title>My website</title>
</head>
</html>
请考虑:
function indentContent($content, $tab="\t"){
$content = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $content); // add marker linefeeds to aid the pretty-tokeniser (adds a linefeed between all tag-end boundaries)
$token = strtok($content, "\n"); // now indent the tags
$result = ''; // holds formatted version as it is built
$pad = 0; // initial indent
$matches = array(); // returns from preg_matches()
// scan each line and adjust indent based on opening/closing tags
while ($token !== false && strlen($token)>0){
$padPrev = $padPrev ?: $pad; // previous padding //Artis
$token = trim($token);
// test for the various tag states
if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)){// 1. open and closing tags on same line - no change
$indent=0;
}elseif(preg_match('/^<\/\w/', $token, $matches)){// 2. closing tag - outdent now
$pad--;
if($indent>0) $indent=0;
}elseif(preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)){// 3. opening tag - don't pad this one, only subsequent tags (only if it isn't a void tag)
foreach($matches as $m){
if (preg_match('/^<(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)/im', $m)){// Void elements according to http://www.htmlandcsswebdesign.com/articles/voidel.php
$voidTag=true;
break;
}
}
$indent = 1;
}else{// 4. no indentation needed
$indent = 0;
}
if ($token == "<textarea>") {
$line = str_pad($token, strlen($token) + $pad, $tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
$result .= $line; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
} elseif ($token == "</textarea>") {
$line = $token; // pad the line with the required number of leading spaces
$result .= $line . "\n"; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
} else {
$line = str_pad($token, strlen($token) + $pad, $tab, STR_PAD_LEFT); // pad the line with the required number of leading spaces
$result .= $line . "\n"; // add to the cumulative result, with linefeed
$token = strtok("\n"); // get the next token
$pad += $indent; // update the pad size for subsequent lines
if ($voidTag) {
$voidTag = false;
$pad--;
}
}
return $result;
}
//$htmldoc - DOMdocument Object!
$niceHTMLwithTABS = indentContent($htmldoc->saveHTML(), $tab="\t");
echo $niceHTMLwithTABS;
将生成具有以下各项的 HTML:
- 基于“级别”的缩进
- 块级元素之后的换行符
- 而内联和自闭合元件不受影响
该函数(这是我使用的类的方法)主要基于:https://stackoverflow.com/a/7840997/7646824