json_encode return null and block code below
Question
I got stuck with a json_encode() problem in PHP.
The simple function below is trying to send the response data to an API call.
function makeResponseOK($data) {
if($data) $response['data'] = $data;
$response['meta'] = ['msg' => 'OK', 'status' => 200];
header('Content-type: application/json');
return json_encode($response, JSON_PRETTY_PRINT);
}
It works perfectly fine on my MAC. However, when I tried to deploy it on my Ubuntu Server, json_encode() does not work at all and any line below json_encode() is neglected. For example:
echo 'crazy';
echo json_encode($data);
echo 'crazy';
will only output one "crazy" to me. I also tried:
echo json_last_error_msg();
echo json_last_error();
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
but none of them give me any result, not even a number...
I have completely no idea what is going on there and I really appreciate if you could help me with it!!!
In addition: My Ubuntu Server's PHP version is 5.5.3 and I am using SLIM framework, idiorm.(Though I don't think it is related...)
Solution
Try to check if json_encode
is actually available on your server. I know it should be there by default, but I ran into some servers where that function was not available.
if (function_exists('json_encode')) {
echo 'Yes';
} else {
echo 'No';
}
OTHER TIPS
Here you have just used json
use json_encode
instead
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr); // Here!
echo json_last_error_msg();
echo json_last_error();