Reputation: 2833
When I try to grab a list of all directories and use the list in a JSON response, I get the error that the response has malformed UTF-8 characters.
I know I have letters like "Æ Ø Å" in the directories. When I use dd($directories)
I can see a "b" infront of every directory that contains a "Æ Ø Å" letter (as you can see in the photo).
I tried to use this, but this does not work either.
return response() -> json($movies, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
Edit: This is the code I have for now.
$drives = ['M1', 'M2', 'M3', 'M4'];
$movies =[];
foreach ($drives as $drive) {
$disk = Storage::disk($drive);
foreach ($disk -> directories() as $movie) {
$movies[] = $movie;
}
}
return response() -> json($movies, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
Upvotes: 2
Views: 32078
Reputation: 40683
You are using strings that are coming from the filesystem filenames. Such strings are typically not in UTF-8 and use the ISO-8859-1 (usually). Coincidentally this is the required input encoding which utf8_encode
requires to work.
$drives = ['M1', 'M2', 'M3', 'M4'];
$movies = [];
foreach ($drives as $drive) {
$disk = Storage::disk($drive);
foreach ($disk -> directories() as $movie) {
$movies[] = utf8_encode($movie);
}
}
return response()->json($movies, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);
However, if you do wish to convert to UTF-8 from another (known) encoding you need to use mb_convert_encoding
. Overall be aware that setting the HTTP response encoding to UTF-8 will not automatically convert any character encodings. You have to do that manually.
Upvotes: 6