Dan*_*ett 0 html php indentation auto-indent view-source
作为一个完美主义者,我喜欢PHP输出有效且正确缩进的HTML.
我有一些具有IT意识的用户的复杂Web应用程序,他们希望能够查看源代码而不会看到乱码.
目前我使用这个函数我写道:
function nl($tabs = 0)
{
return "\r\n" . str_repeat("\t", $tabs);
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它来添加换行符和所需数量的选项卡:
if(array_key_exists('field', $row)){
echo '<td>' . $row['field'] . '</td>' . nl(4);
}
Run Code Online (Sandbox Code Playgroud)
有内置的PHP,还是有一个类可以用来自动进行缩进?
使用输出缓冲区时,可以使用DOMDocument并在将缓冲区刷新到客户端/浏览器之前将formatOutput设置为true.
即:
libxml_use_internal_errors( TRUE );
$dom = new DOMDocument();
$dom->validateOnParse = FALSE;
$dom->preserveWhiteSpace = TRUE;
$dom->formatOutput = TRUE;
$om->loadHTML( mb_convert_encoding( ob_get_contents(), 'UTF-8' ) );
libxml_clear_errors();
/*
perform any other operations on dom elements you wish
*/
$buffer = $dom->saveHTML();
ob_end_clean();
echo trim( $buffer );/* send data to client/browser */
Run Code Online (Sandbox Code Playgroud)