Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override json_encode() functionality in php

Tags:

json

php

I have created total api's using php programming, for the output i used

json_encode($arr),

Now i want to print output as pretty print format in the browser without using JSON Viewer extensions..

I have already completed 400+ webservices using json_encode($arr) to output, but i don't want to change to

 echo json_encode($arr, JSON_PRETTY_PRINT);

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

like image 389
Manikanta Avatar asked Dec 14 '17 10:12

Manikanta


3 Answers

There are some ways to do that by using some extensions like runkit which provide runkit_function_redefine() or apd which provide override_function().

If I were you, I'd simply find/replace the json_encode() calls, adding JSON_PRETTY_PRINT.

like image 121
Romain Ciaccafava Avatar answered Oct 06 '22 05:10

Romain Ciaccafava


An other solution without redefine the json_encode function, you could also simply register an output handler, which reads the printed json and print it again in pretty.

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

Benefit of this solution would be, you don't need any php extensions (as runkit currently dont work in PHP 7)

like image 25
Philipp Avatar answered Oct 06 '22 03:10

Philipp


you can use override_function like this:

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

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

like image 44
Roberto Bisello Avatar answered Oct 06 '22 05:10

Roberto Bisello