我正在使用 json 和 AJAX,以便在不刷新页面的情况下获取一些 HTML。 AJAX 调用调用一个简化的函数是这样的:
function postHTML($post) { // returns the HTML structure for a post starting from an array of variables
# other stuff
require('post.template.php'); // which is mostly HTML with just few php variables embedded
}
$data = '';
foreach ($posts as $post) {
$data .= postHTML($post);
}
之后我按如下方式管理 json:
echo json_encode(array('success' => true, 'data' => $data));
其中数据应该是加载的每个帖子的 HTML 结构。 问题是当我需要 'post.template.php' 文件时,它使用 require 并将数据返回给 Javascript:
[HTML posts] {"success": true, "data": ""}
我怎样才能将 HTML 放入一个变量中,然后将其传递给 json_encode
而实际上不需要页面(仍应作为 PHP 执行)?
最佳答案
您可以使用 Output buffering , around your require, to capture the output, preventing it from being echoed : it'll get stored in memory, and you'll able to fetch it to a variable.
基本上,这意味着使用以下类型的代码:
ob_start();
// Output is no longer sent to the standard output,
// but stored in memory
require('post.template.php');
// Fetch the content that has been stored in memory
$content = ob_get_clean();
作为引用:
关于php - 需要一个 html 页面但不回显它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5343484/