I'm writing a PHP script that can return a JSON response. The problem is that I want to return only the JSON file, like this:
header('Content-Type: application/json');
echo json_encode($data);
Before that there is some HTML loaded (such as the site header). I want to remove that from the content returned by PHP. For example:
echo '<p>foo</p>';
echo '<p>bar</p>';
header('Content-Type: application/json');
echo json_encode($data);
die();
I want to remove everything that was output as plain HTML before I output the JSON file, and then I'll prevent any further code of being output. So the result is returning just a JSON and nothing else that was output before that.
Change your code so that it contains an if-else condition handling if it's a JSON context or not. There should be many better solutions, but we don't know anything about your code structure. You should not output anything before sending HTTP headers, otherwise the "Content-Type: text/html"
or text/plain
will be set automatically.