How to override json_encode () functionality in php

I created a generic api using php programming for the output I used

json_encode($arr), 

Now I want to print the output as a fairly printed format in the browser without using the JSON Viewer extensions.

I have already done 400+ web services using json_encode ($ arr) for output, but I don't want to change

  echo json_encode($arr, JSON_PRETTY_PRINT); 

I just want how to override the default json_encode () predefined functionality to completely fill my need.

+5
source share
3 answers

Another solution without overriding the json_encode function, you can also just register an output handler that reads the printed json and prints it again pretty nicely.

 ob_start(function($json) { return json_encode(json_decode($json), JSON_PRETTY_PRINT); }); 

The advantage of this solution would be that you do not need php extensions (since runkit currently does not work in PHP 7)

+2
source

There are several ways to do this using some extensions, such as runkit , which provide runkit_function_redefine() or apd , which provide override_function() .

If I were you, I would just find / replace json_encode() calls by adding JSON_PRETTY_PRINT .

+3
source

you can use override_function as follows:

 rename_function('json_encode', 'original_json_encode'); override_function('json_encode', '$value, $options = 128, $depth = 512', 'return original_json_encode($value, $options, $depth);'); 

this way you can use the original one to get the result, overriding the default parameters (128 is the value JSON_PRETTY_PRINT ), and you can use json_encode the same way as before

+2
source

Source: https://habr.com/ru/post/1274060/


All Articles