I am using the Slim framework with PHP to create a RESTful API for my app. However, I assumed that the framework would have some way of creating easier JSON outputs rather than
function _die($array){
echo json_encode($array);
exit;
}
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
_die($array);
header("Content-Type : application/json"); echo json_encode($data);
header("Content-Type: application/json");
echo json_encode($result);
exit;
Hint: Using The Slim PHP Framework for Developing REST APIs
Using Slim 3, I'm using this format:
<?php
$app = new \Slim\App();
$app->get('/{id}', function ($request, $response, $args) {
$id = $request->getAttribute('id');
return $response->withJSON(
['id' => $id],
200,
JSON_UNESCAPED_UNICODE
);
});
On request "/123", result JSON with:
{
id: "123"
}
More infos read here.
[UPDATE]
Added second and third param to withJSON
. Second is The HTTP status code, and third is Json encoding options (best for especial chars and others, for example: print "ã" correctly)
I think Slim also provides a middleware object which does this automatically so users of that framework doesnt have to write json_decode and encode on every request, its called the
Slim_Middleware_ContentType
object.
$app->response()->('application/json');
$app->add(new Slim_Middleware_ContentType());
it does the decoding for you. the decoding works great.But for encoding the last post is great.
Thanks, Dharani
My fix was adding "exit;" at the end of the json print out, my dev server didn't care, but my live server would not trigger the json end event. I did not need to add headers or use json_encode.