Storing an html page into a php variable

g0dl3ss picture g0dl3ss · Jan 2, 2012 · Viewed 7.5k times · Source

Hi i'd like to store a dinamically generated(with php) html code into a variable and be able to send it as a reply to an ajax request. Let's say i randomly generate a table like:

<?php 
$c=count($services);
?>
<table>
<?php
for($i=0; $i<$c; $i++){
 echo "<tr>";
 echo "<td>".$services_global[$i][service] ."</td>";
 echo "<td>".$services_global[$i][amount]."</td>";
 echo "<td>&euro; ".$services_global[$i][unit_price].",00</td>";
 echo "<td>&euro; ".$services_global[$i][service_price].",00</td>";
 echo "<td>".$services_global[$i][service_vat].",00%</td>";
 echo "</tr>";
}
?>
</table>

I need to store all the generated html code(and the rest) and echo it as a json encoded variable like:

$error='none';
$result = array('teh_html' => $html, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;

I could maybe generate an html file and then read it with:

ob_start();
//all my php generation code and stuff
file_put_contents('./tmp/invoice.html', ob_get_contents());
$html = file_get_contents('./tmp/invoice.html');

But it sounds just wrong and since i don't really need to generate the code but only send it to my main page as a reply to an ajax request it would be a waste of resources. Any suggestions?

Answer

maček picture maček · Jan 2, 2012

You don't have to store it in a file, you can just use the proper output buffering function

// turn output buffering on
ob_start();

// normal output
echo "<h1>hello world!</h1>";

// store buffer to variable and turn output buffering offer
$html = ob_get_clean();

// recall the buffered content
echo $html; //=> <h1>hello world!</h1>

More about ob_get_clean()