用PHP解码UTF-16

时间:2014-07-04 09:57:14

标签: php character-encoding utf-16

我偶然发现了一段用Python编写的有趣代码:

from struct import pack

chars = [109, 0, 97, 0, 110, 0, 105, 0, 102, 0, 101, 0, 115, 0, 116, 0]
length = 16

data = ""
for i in range(0, length):
    ch = pack("=b", chars[i])
    data += unicode(ch, errors='ignore')

    if data[-2:] == "\x00\x00":
        break

end = data.find("\x00\x00")
if end != -1:
    data = data[:end]

print(len(data.decode("utf-16", "replace"))) // outputs 8, string is 'manifest'

如您所见,Python确实正确解码utf-16。 但是,当我尝试将代码移植到PHP时,我得到了不好的结果:

$chars = array(109, 0, 97, 0, 110, 0, 105, 0, 102, 0, 101, 0, 115, 0, 116, 0);
$length = 16;

$data = "";
for ($i = 0; $i < $length; $i++) {
    $data .= pack("c", $chars[$i]);

    if (substr($data, -2) == "\x00\x00") {
        break;
    }
}

$end = strpos($data, "\x00\x00");
if ($end !== false) {
    $data = substr($data, 0, $end);
}

// md_convert_encoding() doesn't seem to work
printf(strlen($data)); // outputs 16

我看到的唯一解决方案是放弃UTF魔法并将循环更改为:

for ($i = 0; $i < $length; $i+=2)

我能做些什么,或者只是使用修改过的for循环?

谢谢。

1 个答案:

答案 0 :(得分:2)

首先看一下How can I convert array of bytes to a string in PHP?

使用该解决方案,您可以将字节数组转换为类似

的字符串
$chars = array(109, 0, 97, 0, 110, 0, 105, 0, 102, 0, 101, 0, 115, 0, 116, 0);
$str = call_user_func_array("pack", array_merge(array("C*"), $chars));
$convertedStr = iconv('utf-16', 'utf-8', $str);

var_dump($str);
var_dump($convertedStr);

执行此脚本输出

string(16) "manifest"
string(8) "manifest"