将 html 页面存储到 php 变量中
您好,我想将动态生成的(使用 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>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$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 请求的回复,这会浪费资源。 有什么建议吗?
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>€ ".$services_global[$i][unit_price].",00</td>";
echo "<td>€ ".$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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不必将其存储在文件中,只需使用正确的输出缓冲函数
有关 ob_get_clean() 的更多信息
You don't have to store it in a file, you can just use the proper output buffering function
More about ob_get_clean()
如果数据的重新生成成本如此之高,那么我建议您使用 memcached。
否则我会每次都重新生成它或将其缓存在前端。
if the data is so much expensive to regenerate then I would suggest you to use memcached.
Otherwise I would go regenerate it every-time or cache it on the frontend.