简体   繁体   中英

Laravel malformed character UTF-8

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);

在此处输入图片说明

You are using strings that are coming from the filesystem filenames. Such strings are typcally 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($str,"UTF-8",$from_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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM