【问题标题】:echoing mid execution is not being sent to the recipient回显中间执行未发送给收件人
【发布时间】:2018-05-19 09:29:57
【问题描述】:
$output = ob_get_contents();
        ob_end_clean();
        echo json_encode($data);
        ob_start();
        echo $output;

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

【问题讨论】:

  • 我想我试过了,但我想立即将json_encode($data) 发送回请求此脚本的服务器,因此我不想为此使用输出缓冲。

标签: php echo ob-start ob-get-contents


【解决方案1】:

怎么样:

将结果存储在变量中,回显变量,记录变量。无需输出缓冲:

$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);

但无论哪种情况,对于简单的第一个解决方案,这些似乎都是繁琐的替代方案,至少在您提出的场景中是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2016-05-21
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多