I know the output generated by PHP will follow the way my code is written. For instance :
echo '<div id="test">';
echo '<div id="other-test>';
echo '</div>';
echo '</div>';
Will output something like
<div id="test">
<div id="other-test">
</div>
</div>
Is there a way to generate something like this instead, without change my code ?
<div id="test"><div id="other-test"></div></div>;
Would be something like grunt do with .js files.
I know i could change my source code to get this output, but this would make the code harder to read during developing.
Why i want to do this ? Because if i open the source of html output of my app, i see a lot of line breaks and blank spaces and i think if i could get ride of it, less network traffic would be required.
Thanks !
I'd use output buffering. You've got something like this
<?php
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
First, at the start of your code add a call to start output buffering. This will prevent PHP from sending output.
<?php
ob_start();
echo '<div id="test">';
echo '<div id="other-test>';
//a lot of other complicated output logic
echo '</div>';
echo '</div>';
Then, at the end of the long complicated output code, use 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();
The call to ob_get_clean
will discard the output buffer (PHP won't echo anything) but return the contents of the output buffer before doing so (ie $output
will have a string of what would have been output).
You're then free to modify the the string all you like before echo
ing it yourself
<?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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.