0

如何像谷歌页面速度一样缩小我的 php 页面 html 输出?

例子:

<!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 ob_start,这个 html 输出怎么会变成这样?

<!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

4 回答 4

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>";
于 2012-10-15T20:22:31.773 回答
0

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

这很有用:如何从 PHP 中的文本中删除空行?

于 2012-10-15T19:38:17.300 回答
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;
?>

希望有帮助!

于 2012-10-15T19:44:22.687 回答
0

尝试使用一些js,有时它很有用

于 2012-10-15T19:50:32.247 回答