This is because the rest API internally uses json_encode()
to output the data. There are 2 ways that you can resolve this.
1. Prevent the API from sending the data
This might be a bit odd and raise some issues, but you can set the header type and echo the content before returning the data:
header( 'Content-Type: text/event-stream' );
header( 'Cache-Control: no-cache' );
// Echo whatever data you got here
// Prevent the API from continuing
exit();
Since this is not the standard way to use the API, it might cause some issues. I haven’t tried this myself.
2. Use admin-ajax.php
Instead of the rest API, use the admin AJAX. The implementation is the same. Basically if you use json_encode()
alongside with die();
you’ll get the same results as rest API. The codex page on this topic covers almost everything. By using admin AJAX, you can fully control the headers and output type.