wp_send_json
just does a basic data sanitization under the hood using wp_json_encode
function.
So you can use PHP’s built-in functionality json_encode
the problem that you’re going to have is keeping the connection alive, If you’re not going to have a lot of visitors you can block the PHP thread by simply running a while true loop and echo data whenever it’s ready.
while(true) {
// BTW, You'll have to handle your data within the loop or in an outer process
if($data_available) {
echo json_encode($data);
if($last_item) {
wp_die();
}
}
}
You have to make sure you’re sending Keep-Alive
header and are tuning your script to provide sufficient requirements for this protocol feature.
Writing this code inside the WordPress’s core is a little bit hard and might get confusing in the future, there is an alternative solution to this problem.
It’s better to use a duplex protocol (like WebSocket) for this kind of data (which are getting ready over the time).
In PHP there is a very good library to write reactive code called ReactPHP
, You can simply integrate it with another library called React Socket
or Ratchet
(I can’t remember correctly if ratchet does handle all stuff by it self or not).