如何在不删除非空换行符的情况下缩小php html输出?

时间:2012-10-15 19:35:38

标签: php html minify

如何缩小我的php页面html输出,如google page speed吗?

示例:

<!DOCTYPE html>
<html>

<head>
<title>Untitled Document</title>

<meta name="description" content="Phasellus rhoncus euismod libero a lacinia. Lorem ipsum dolor sit amet, consectetur adipiscing elit." />

</head>

<body>
<div id="content">
<div id="post-1">
<h1>Phasellus rhoncus euismod libero a lacinia.</h1>
<p>...</p>
</div>

<div id="post-2">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>...</p>
</div>

</div>


</body>
</html>

这个html输出如何使用php ob_start变成这样的东西?

<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title> 
<meta name="description" content="Phasellus rhoncus euismod libero a lacinia. Lorem ipsum dolor sit amet, consectetur adipiscing elit." />
</head>
<body>
<div id="content">
<div id="post-1">
<h1>Phasellus rhoncus euismod libero a lacinia.</h1>
<p>...</p>
</div>
<div id="post-2">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>...</p>
</div>
</div>
</body>
</html>

编辑:

我已尝试过此代码(基于James Pegg的回答)

function sanitize_output($buffer){
$search = array("\n", "\t");
return preg_replace($search, '', $buffer);}

ob_start("sanitize_output");

但它不起作用。该页面现在为空。

最终工作代码(基于W. Kristianto的回答):

function sanitize_output($buffer){
$buffer = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $buffer);
return $buffer;}

4 个答案:

答案 0 :(得分:1)

$data = '
<!DOCTYPE html>
<html>

<head>
<title>Untitled Document</title>

<meta name="description" content="Phasellus rhoncus euismod libero a lacinia. Lorem ipsum dolor sit amet, consectetur adipiscing elit." />

</head>

<body>
<div id="content">
<div id="post-1">
<h1>Phasellus rhoncus euismod libero a lacinia.</h1>
<p>...</p>
</div>

<div id="post-2">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>...</p>
</div>

</div>


</body>
</html>';

echo "<pre>";
echo htmlentities(preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $data));
echo "</pre>";

答案 1 :(得分:0)

只需删除仅包含\r\n\r\n的每一行。

这很有用:How do I remove blank lines from text in PHP?

答案 2 :(得分:0)

您可以取出所有新行和标签:

<?php
// Start Output Bugger
ob_start();

// Start HTML Output
?>
<!DOCTYPE html>
<html>

<head>
<title>Untitled Document</title>

<meta name="description" content="Phasellus rhoncus euismod libero a lacinia. Lorem ipsum dolor sit amet, consectetur adipiscing elit." />

</head>

<body>
<div id="content">
<div id="post-1">
<h1>Phasellus rhoncus euismod libero a lacinia.</h1>
<p>...</p>
</div>

<div id="post-2">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h1>
<p>...</p>
</div>

</div>


</body>
</html>

<?php

// Save Output bugger as a variable
$html = ob_get_clean();

//Array of characters to replace
$strings = Array("\n", "\t");

//Strip out new lines and tabs
$html = str_replace($strings, '', $html);

//Echo minified content
echo $html;
?>

希望有所帮助!

答案 3 :(得分:0)

尝试使用一些js library,有时使用它的