回声中执行不会发送给收件人


$output = ob_get_contents();
        ob_end_clean();
        echo json_encode($data);
        ob_start();
        echo $output;

此代码从另一台服务器称为API,我想将JSON数据发送回该服务器,但我想将$输出保留在输出缓冲区中,以便以后可以将其记录到文件中。json_encode($data);没有发送到请求脚本。我尝试使用flush()ob_flush尝试了许多变体,但没有起作用。当我在json_encode($data);行之后立即添加die()时,它可以正常工作,除了我实际上不希望它到die()。我怎样才能解决这个问题?

at:

将结果存储在变量中,回声变量,日志变量。无需输出缓冲:

$output = json_encode($data);
echo $output;
log_to_whatever($output);

如果您确实需要输出缓冲,则应在回声之前开始缓冲:

ob_start();
echo json_encode($data);
$output = ob_get_clean(); // Shorthand for get and clean
echo $output;
log_to_whatever($output);

而不是清洁缓冲区,您实际上可以冲洗缓冲区(=将其发送给客户端),但仍然将其放入变量。

ob_start();
echo json_encode($data);
$output = ob_get_flush(); // Shorthand for get and flush
// echo $output; This is not needed anymore, because it is already flushed
log_to_whatever($output);

但是,无论哪种情况,似乎都是简单的第一个解决方案的繁琐替代方案,至少在您提出的情况下。

最新更新