I am learning how to build an API using PHP and Slim Framework, I made a test called "data" to get an array:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: text/html; charset=utf-8');
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
error_reporting(1);
require '../../slim/vendor/autoload.php';
$app = new \Slim\App;
function response($status_code, $response) {
$app = \Slim\App::getInstance();
$app->status($status_code);
$app->contentType('application/json');
return json_encode($response);
}
$app->get('/data', function () {
$response = array();
$data=array(
array('Foo'=>'Foo', 'Bar'=>'Bar'),
array('Lorem'=>'Ipsum', 'Dolor'=>'Sit Amet')
);
$response["error"] = false;
$response["message"] = "datas: " . count($data);
$response["data"] = $data;
return response(200, $response);
});
When I call the api using /data I got a status 200 empty response.
This is the url: http://sandboxweb.bailac.net/gts_benja/api/v1/data
What is wrong and what I need to do to get the array?
Don't echo
the response, return
it:
function response($status_code, $response) {
$app = \Slim\App::getInstance();
$app->status($status_code);
$app->contentType('application/json');
return json_encode($response);
}
And then in your handler function:
return response(200, $response);
Well, I finally got it, Slim 3 needs return a slim object (like body, write and withJson), the following code works for me:
$app->get('/data', function ($request, $response){
$data=array(
array('Foo'=>'Foo', 'Bar'=>'Bar'),
array('Lorem'=>'Ipsum', 'Dolor'=>'Sit Amet')
);
return $response->withJson($data);
});
the followings ways to return worked for me too:
return $response->body(json_encode($data));
return $response->write(json_encode($data));
I prefer withJson
method to avoid using json_encode
.
Thank you Alex Howansky for your help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.