Thursday, October 25, 2018

Returning JSON from a PHP Script



I want to return JSON from a PHP script.



Do I just echo the result? Do I have to set the Content-Type header?



Answer



While you're usually fine without it, you can and should set the Content-Type header:



$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);


If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...