如何将字节数组转换为 PHP 中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5473011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert array of bytes to a string in PHP?
提问by Damir
I have an array of bytes that I'd like to map to their ASCII equivalents.
我有一个字节数组,我想将它们映射到它们的 ASCII 等效项。
How can I do this?
我怎样才能做到这一点?
回答by mario
If by array of bytes you mean:
如果通过字节数组,您的意思是:
$bytes = array(255, 0, 55, 42, 17, );
array_map()
数组映射()
Then it's as simple as:
那么就这么简单:
$string = implode(array_map("chr", $bytes));
foreach()
foreach()
Which is the compact version of:
这是以下的精简版:
$string = "";
foreach ($bytes as $chr) {
$string .= chr($chr);
}
// Might be a bit speedier due to not constructing a temporary array.
pack()
盒()
But the most advisable alternative could be to use pack("C*", [$array...])
, even though it requires a funky array workaround in PHP to pass the integer list:
但最可取的替代方法可能是使用pack("C*", [$array...])
,即使它需要在 PHP 中使用时髦的数组解决方法来传递整数列表:
$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));
That construct is also more useful if you might need to switch from bytes C*(for ASCII strings) to words S*(for UCS2) or even have a list of 32bit integers L*(e.g. a UCS4 Unicode string).
如果您可能需要从字节C*(对于 ASCII 字符串)切换到单词S*(对于 UCS2),或者甚至需要一个 32 位整数列表L*(例如 UCS4 Unicode 字符串),那么该构造也更有用。
回答by Eaton Emmerich
Ammending the answer by mario for using pack()
:
Since PHP 5.5, you can use Argument unpacking via ...
修改 mario 使用的答案pack()
:自 PHP 5.5 起,您可以使用 Argument unpacking via...
$str = pack('C*', ...$bytes);
The other functions are fine to use, but it is preferred to have readable code.
其他函数都可以使用,但最好有可读的代码。
回答by Alix Axel
Yet another way:
还有一种方式:
$str = vsprintf(str_repeat('%c', count($bytes)), $bytes);
Hurray!
欢呼!
回答by alex
回答by Ofek Cohany
Below is an example of converting Yodlee MFA ByteArray to CAPTCHA image. Hope it helps someone...
下面是将 Yodlee MFA ByteArray 转换为 CAPTCHA 图像的示例。希望它可以帮助某人...
You simply have to convert the byte array to string, then encode to base64.
您只需将字节数组转换为字符串,然后编码为 base64。
Here is a PHP example:
这是一个 PHP 示例:
$byteArray = $obj_response->fieldInfo->image; //Here you get the image from the API getMFAResponse
$string = implode(array_map("chr", $byteArray)); //Convert it to string
$base64 = base64_encode($string); //Encode to base64
$img = "<img src= 'data:image/jpeg;base64, $base64' />"; //Create the image
print($img); //Display the image