问题描述
如何将字节数组转换为UTF-8字符串?我需要这个,因为我是从二进制格式中提取的.
How can I convert an array of bytes into a UTF-8 string? I need this because I am extracting from a binary format.
推荐答案
字符串不过是字节数组.因此,UTF-8字符串与字节数组非常相似,不同之处在于您还知道字节数组代表什么.
A string is nothing more than an array of bytes. So a UTF-8 string is the very same as an array of bytes, except that in addition you know what the array of bytes represent.
因此,您输入的字节数组还需要其他信息:字符集(字符编码).如果您知道输入字符集,则可以将字节数组转换为代表UTF-8字符串的另一个字节数组.
So your input array of bytes needs one more additional information as well: the character set (character encoding). If you know the input character set, you can convert the array of bytes to another array of bytes representing an UTF-8 string.
用于执行此操作的PHP方法称为 mb_convert_encoding()
.
The PHP method for doing that is called mb_convert_encoding()
.
PHP本身不知道字符集(字符编码).因此,字符串实际上无非就是字节数组.该应用程序必须知道如何处理.
PHP itself does not know of character sets (character encodings). So a string really is nothing more than an array of bytes. The application has to know how to handle that.
因此,如果您有一个字节数组,并且想将其转换为PHP字符串,以便使用mb_convert_encoding()
转换字符集,请尝试以下操作:
So if you have an array of bytes and want to turn that into a PHP string in order to convert the character set using mb_convert_encoding()
, try the following:
$input = array(0x53, 0x68, 0x69);
$output = '';
for ($i = 0, $j = count($input); $i < $j; ++$i) {
$output .= chr($input[$i]);
}
$output_utf8 = mb_convert_encoding($output, 'utf-8', 'enter input encoding here');
(而不是上面的单个示例,请在 https://stackoverflow.com/a/5473057/上查看更多示例530502 .)
(Instead of the single example above, have a look at more examples at https://stackoverflow.com/a/5473057/530502.)
$output_utf8
将是输入字节数组的PHP字符串,该字节数组转换为UTF-8.
$output_utf8
then will be a PHP string of the input array of bytes converted to UTF-8.
这篇关于字节数组到PHP中的UTF-8字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!