如何丑化/缩小 PHP 输出?
How to uglify / minify PHP output?
我知道 PHP 生成的输出将遵循我编写代码的方式。例如:
echo '<div id="test">';
echo '<div id="other-test>';
echo '</div>';
echo '</div>';
会输出类似
的内容
<div id="test">
<div id="other-test">
</div>
</div>
有没有办法在不更改我的代码的情况下生成类似这样的东西?
<div id="test"><div id="other-test"></div></div>;
类似于 grunt 对 .js 文件的处理。
我知道我可以更改我的源代码以获得此输出,但这会使代码在开发过程中更难阅读。
为什么我要这样做?因为如果我打开我的应用程序 html 输出的来源,我会看到很多换行符和空格,我想如果我能驾驭它,将需要更少的网络流量。
谢谢!
我会使用输出缓冲。你有这样的东西
<?php
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
首先,在代码的开头添加一个调用以启动输出缓冲。这将阻止 PHP 发送输出。
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
然后,在冗长复杂的输出代码的最后,使用ob_get_clean()
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
$output = ob_get_clean();
对 ob_get_clean
的调用将丢弃输出缓冲区(PHP 不会回显任何内容)但是 return 在这样做之前输出缓冲区的内容(即 $output
将有一串将被输出的内容)。
然后您可以随意修改字符串,然后再echo
自己编辑
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
$output = ob_get_clean();
//remove newlines and carriage returns
$output = str_replace("\r", '', $output);
$output = str_replace("\n", '', $output);
$output = someOtherMinifyFunction($output);
echo $output;
我知道 PHP 生成的输出将遵循我编写代码的方式。例如:
echo '<div id="test">';
echo '<div id="other-test>';
echo '</div>';
echo '</div>';
会输出类似
的内容<div id="test">
<div id="other-test">
</div>
</div>
有没有办法在不更改我的代码的情况下生成类似这样的东西?
<div id="test"><div id="other-test"></div></div>;
类似于 grunt 对 .js 文件的处理。
我知道我可以更改我的源代码以获得此输出,但这会使代码在开发过程中更难阅读。
为什么我要这样做?因为如果我打开我的应用程序 html 输出的来源,我会看到很多换行符和空格,我想如果我能驾驭它,将需要更少的网络流量。
谢谢!
我会使用输出缓冲。你有这样的东西
<?php
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
首先,在代码的开头添加一个调用以启动输出缓冲。这将阻止 PHP 发送输出。
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
然后,在冗长复杂的输出代码的最后,使用ob_get_clean()
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
$output = ob_get_clean();
对 ob_get_clean
的调用将丢弃输出缓冲区(PHP 不会回显任何内容)但是 return 在这样做之前输出缓冲区的内容(即 $output
将有一串将被输出的内容)。
然后您可以随意修改字符串,然后再echo
自己编辑
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
$output = ob_get_clean();
//remove newlines and carriage returns
$output = str_replace("\r", '', $output);
$output = str_replace("\n", '', $output);
$output = someOtherMinifyFunction($output);
echo $output;