php Laravel 格式错误的字符 UTF-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38307155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:32:43  来源:igfitidea点击:

Laravel malformed character UTF-8

phpjsonlaravelutf-8

提问by Kaizokupuffball

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

当我尝试获取所有目录的列表并在 JSON 响应中使用该列表时,我收到错误消息,即响应的 UTF-8 字符格式错误。我知道我有像“???”这样的字母 在目录中。当我使用时,dd($directories)我可以看到每个包含“? ? ?”的目录前面都有一个“b”。信(如您在照片中所见)。

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

我尝试使用它,但这也不起作用。 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);

enter image description here

在此处输入图片说明

回答by apokryfos

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_encoderequires to work.

您正在使用来自文件系统文件名的字符串。此类字符串通常不在 UTF-8 中并使用 ISO-8859-1(通常)。巧合的是,这是utf8_encode工作所需的输入编码。

$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.

但是,如果您确实希望从另一种(已知)编码转换为 UTF-8,则需要使用mb_convert_encoding($str,"UTF-8",$from_encoding). 请注意,将 HTTP 响应编码设置为 UTF-8 不会自动转换任何字符编码。您必须手动执行此操作。