phpjsoncompressiongzipfile-get-contents

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


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?


Solution

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

    echo json_encode(json_decode($data));
    

    This will strip all whitespaces