I'm trying to make an REST API with my GET function and I'm trying to retrieve the information of my database that I have in phpMyAdmin. I'm using Slim Framework.
The problem is when I try to retrieve the information of my database (that is encoded in utf8_general_ci
) with json_encode
. When I try to access to this GET function by URL, I just see a blank page. I found where the problem is, because I used a var_dump($users);
at the line before the json_encode
and it retrieved me the information that I have stored in my database.
I searched and I found that I could get the error that was giving my json_encode
with json_last_error
function so I did it.
echo json_encode($users);
echo json_last_error();
And it returns to me a 5, that means: JSON_ERROR_UTF8
.
Then I searched and I saw that it is a problem of the encoding, that maybe it's made wrong but I couldn't get any solution to solve my problem.
My GET method of my REST API is:
<?php
if(!defined("SPECIALCONSTANT")) die("Access denied");
$app->get("/users/",function() use($app)
{
try{
$connection = getConnection();
$dbh = $connection->prepare("SELECT * FROM users");
$dbh->execute();
$users = $dbh->fetchAll();
$connection = null;
$app->response->headers->set("Content-type","application/json");
$app->response->status(200);
$app->response->body(json_encode($users));
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
});
What I tried:
Change this:
$app->response->headers->set("Content-type","application/json"); $app->response->status(200); $app->response->body(json_encode($users));
to this:
header("HTTP/1.1 200"); header("Content-Type:application/json; charset=utf-8"); echo json_encode($users);
Change the charset to
utf8mb4
but it doesn't work.- Tried to use
json_encode($users, JSON_UNESCAPED_UNICODE );
but the result was the same.
I think the encode could be wrong because I use spanish characters on my database like ñ
or ó é á ú
but I saw that the recomended encode for my database with spanish characters was utf8_general_ci
.
Does utf8_general_ci
have a special charset? Do you know another way to retrieve the information from my database with json_encode? With all the possible solutions that I tried before I got a blank page.