将html页面存储到php变量中

时间:2012-01-02 20:16:10

标签: php html ajax json storing-data

您好我想将一个动态生成的(带有php)html代码存储到变量中,并能够将其作为对ajax请求的回复发送。 假设我随机生成一个表格,如:

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

我需要存储所有生成的html代码(以及其余的代码)并将其作为json编码变量回显,如:

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

我可以生成一个html文件,然后用:

读取它
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');

但这听起来是错的,因为我不需要生成代码,只是将其作为对ajax请求的回复发送到我的主页面,这将浪费资源。 有什么建议吗?

3 个答案:

答案 0 :(得分:9)

您不必将其存储在文件中,只需使用正确的输出缓冲功能

即可
// 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()

答案 1 :(得分:0)

如果重新生成的数据非常昂贵,那么建议您使用memcached

否则我会每次都重新生成它或将其缓存在前端。

答案 2 :(得分:0)

for($i=0;$i<=5;$i++)
{
    ob_start();
    $store_var = $store_var.getdata($i); // put here your recursive function name
    ob_get_clean();
}

function getdata($i)
{
    ?>
    <h1>
    <?php
      echo $i;
    ?>
    </h1>
    <?php
    ob_get_contents();
}
相关问题