Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP最佳实践之多字节字符串、字符编码 #8

Open
xx19941215 opened this issue Jul 20, 2017 · 0 comments
Open

PHP最佳实践之多字节字符串、字符编码 #8

xx19941215 opened this issue Jul 20, 2017 · 0 comments

Comments

@xx19941215
Copy link
Owner

xx19941215 commented Jul 20, 2017

多字节字符串

1).PHP假设字符串中的每一个字符都是八位字符,占用一个字节的内存。但是,你有可能会遇到多字节字符串。
2).这里所说的多字节字符串是指不在传统的128个ASCII字符集中的字符。如果使用PHP原生的字符串函数处理这些多字节Unicode字符串,会得到意外的错误。
3).安装mbstring扩展来处理这些问题。例如使用处理多字节的字符串函数mb_strlen()函数来替代原生的strlen()函数。

字符编码

1).一定要知道数据的字符编码。
2).使用UTF-8字符编码存储数据。
3).使用UTF-8字符编码输出数据。
4).mbstring扩展不仅可以处理Unicode字符串,还可以在不同的字符编码之间转换多字节字符串。

输出UTF-8数据

1).在php.ini中作如下配置

default_charset = "UTF-8";

2)例如header函数明确指定字符集,在PHP返回的响应中,Content-Type首部默认也使用了这个默认值

<?php
header('Content-Type: application/json;charset=utf-8');

3).只要PHP已经明确返回了输出,就不能使用header()函数了
4).建议在HTML文档的头部也加入响应的meta标签

<meta charset="UTF-8"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant