PHP encountered a magical problem caused by Chinese garbled characters
大家讲道理
大家讲道理 2017-05-31 10:33:23
0
2
933

for example

$data = 'Baidu�Tencent,Alibaba';

$data1 // It is a variable. When printed, it is 'Baidu�Tencent, Alibaba'

var_dump($data);
var_dump($data1);

Print results:
$data: string(24) "Baidu�Tencent, Alibaba"
$data1:string(22) "Baidu�Tencent, Alibaba"

$keywordsData = json_encode($data, JSON_UNESCAPED_UNICODE);
$keywordsData1 = json_encode($data1, JSON_UNESCAPED_UNICODE);
var_dump($keywordsData);
var_dump($keywordsData1);

Print results:
keywordsData:string(26) ""Baidu�Tencent,Alibaba""
keywordsData1:bool(false)

Why is this? I want to get the variable directly, but now I encounter this problem, please answer, thank you

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
phpcn_u1582
$data:string(24) "百度�腾讯,阿里"  //这里8个字符,utf-8中的中文占3个字符,因此长度为24
$data1:string(22) "百度�腾讯,阿里" //这里长度为 22,说明不是utf-8 而json_encode不支持非utf-8字符
//输出错误看看
var_dump(json_last_error());
習慣沉默

The two variables are different. Although they are both strings, one has a length of 24 and the other has a length of 22. The second one is obviously not UTF8 encoded. json_encode will of course be wrong.

You can first detect the string encoding, mb_detect_encoding, and then convert it to UTF8, mb_convert_encoding.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!