$output = ob_get_contents();
ob_end_clean();
echo json_encode($data);
ob_start();
echo $output;
This code is called as an API from another server and I want to send the json data back to that server but I want to keep $output in the output buffer so later I can log it into a file. The json_encode($data);
is not being sent to the requesting script. I have tried many variations using flush()
and ob_flush
but not have worked. When I add die()
immediately after the json_encode($data);
line it works except I don't actually want it to die()
at that moment. how can I fix this?
What about:
Store the result in a variable, echo the variable, log the variable. No need for output buffering:
$output = json_encode($data);
echo $output;
log_to_whatever($output);
If you do want output buffering, then you should start buffering before you echo:
ob_start();
echo json_encode($data);
$output = ob_get_clean(); // Shorthand for get and clean
echo $output;
log_to_whatever($output);
Instead of cleaning the buffer you can actually flush the buffer (= send it to the client), but still get it into a variable too.
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);
But in either case, it seems these are cumbersome alternatives for the simple first solution, at least in the scenario you presented.