wp_set_internal_encoding()
云策文档标注
概述
wp_set_internal_encoding() 函数用于设置 PHP 的内部字符编码,以确保与 WordPress 的字符集(如 UTF-8)兼容,避免使用默认的 latin1 编码导致问题。
关键要点
- 函数检查 mb_internal_encoding 是否可用,优先使用 blog_charset 选项值设置编码。
- 如果 blog_charset 无效或设置失败,则默认回退到 UTF-8 编码。
- 此函数在 WordPress 3.0.0 版本中引入,旨在支持多字节字符串函数(如 mb_* 函数)的正确操作。
代码示例
function wp_set_internal_encoding() {
if ( function_exists( 'mb_internal_encoding' ) ) {
$charset = get_option( 'blog_charset' );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( ! $charset || ! @mb_internal_encoding( $charset ) ) {
mb_internal_encoding( 'UTF-8' );
}
}
}注意事项
函数使用 @ 操作符抑制错误,但代码标准建议避免此做法;开发者应确保 blog_charset 选项正确配置以避免编码问题。
原文内容
Sets internal encoding.
Description
In most cases the default internal encoding is latin1, which is of no use, since we want to use the mb_ functions for utf-8 strings.
Source
function wp_set_internal_encoding() {
if ( function_exists( 'mb_internal_encoding' ) ) {
$charset = get_option( 'blog_charset' );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( ! $charset || ! @mb_internal_encoding( $charset ) ) {
mb_internal_encoding( 'UTF-8' );
}
}
}
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Introduced. |