Is there a way in PHP to strip whitespace from JSON without using ob_gzhandler?

And Finally picture And Finally · Jan 30, 2014 · Viewed 9.4k times · Source

I'm grabbing some JSON data using file_get_contents and I need to compress it so I can add it as a data attribute on an HTML element in my page. Basically I just need to strip out line breaks, extra spaces or tabs. Everybody seems to suggest using ob_gzhandler. But I can't do that - I don't have control over the modules that are enabled on our production environment. Can anybody suggest a PHP snippet that'll do what I want without ob_gzhandler?

Answer

Jesper Blaase picture Jesper Blaase · Jan 30, 2014

If you want the data written as JSON you could do a simple:

echo json_encode(json_decode($data));

This will strip all whitespaces