HOWTO · PHP

PHP UTF-8 转换

本教程演示了如何使用不同的方法将字符串转换为 utf-8 编码。

UTF-8 是一种编码 Unicode 字符的方法,每个字符在一到四个字节之间。

它用于处理特殊字符或来自非英语语言的字符。

PHP 有不同的方法将文本转换为 UTF-8

在 PHP 中使用 utf8_encode()utf8_decode() 编码和解码字符串

utf8_encode()utf8_decode() 都是 PHP 中的内置函数。

它用于编码和解码 ISO-8859-1,以及其他类型的字符串到 UTF-8,这两个函数都以字符串作为参数。

请参见下面的示例:

<?php
$demo="\xE0\xE9\xED"; //ISO-8859-1 String àéí
echo "UTF-8 Encoded String: ";
echo utf8_encode($demo) ."<br>";
echo "UTF-8 Decoded String: ";
echo utf8_decode(utf8_encode($demo)) ."<br>";
echo "UTF-8 Encoded String from the decoded: ";
echo utf8_encode(utf8_decode(utf8_encode($demo))) ."<br>";
?>

上面的代码将一个 ISO-8859-1 字符串编码为 UTF,然后再次解码输出。你看到的输入字符串采用 ISO-8859-1 编码。

输出:

UTF-8 Encoded String: àéí
UTF-8 Decoded String: ���
UTF-8 Encoded String from the decoded: àéí

utf8_decode() 将带有 ISO-8859-1 字符的字符串用 UTF-8 编码转换为单字节 ISO-8859-1

在将 ISO-8859-1 编码文本读取为 UTF-8 时,你经常会看到那个问号。

使用 iconv() 将字符串转换为 UTF-8

iconv() 是另一个内置的 PHP 函数,用于从一个 Unicode 转换字符串。

它需要三个参数,一个是字符串的 Unicode,第二个是你要转换的 Unicode,第三个是字符串本身。

请参见下面的示例:

<?php
$demo="\xE0\xE9\xED"; //ISO-8859-1 String àéí

echo "The UTF-8 String is: ";
echo iconv("ISO-8859-1", "UTF-8", $demo)."<br>";
//mb_detect_encoding() is a function used to detect encoding of the given text.
echo "The UTF-8 String with auto detection is: ";
echo iconv(mb_detect_encoding($demo, mb_detect_order(), true), "UTF-8", $demo);
?>

上面的代码采用三个参数并将文本转换为 UTF-8

输出:

The UTF-8 String is: àéí
The UTF-8 String with auto detection is: àéí

PHP 还提供了其他函数,如 recode_string()mb_convert_encoding(),其工作方式类似于 iconv;他们将字符串转换为请求的 Unicode。