Damir
Damir

Reputation: 56199

How can I convert array of bytes to a string in PHP?

I have an array of bytes that I'd like to map to their ASCII equivalents.

How can I do this?

Upvotes: 31

Views: 71356

Answers (5)

Ofek Cohany
Ofek Cohany

Reputation: 1

Below is an example of converting Yodlee MFA ByteArray to CAPTCHA image. Hope it helps someone...

You simply have to convert the byte array to string, then encode to base64.

Here is a PHP example:

$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

Upvotes: 0

Eaton Emmerich
Eaton Emmerich

Reputation: 539

Ammending the answer by mario for using pack(): Since PHP 5.5, you can use Argument unpacking via ...

$str = pack('C*', ...$bytes);

The other functions are fine to use, but it is preferred to have readable code.

Upvotes: 11

Alix Axel
Alix Axel

Reputation: 154543

Yet another way:

$str = vsprintf(str_repeat('%c', count($bytes)), $bytes);

Hurray!

Upvotes: 2

alex
alex

Reputation: 490213

Mario has already provided the best fit, but here is a more exotic way to achieve this.

$str = call_user_func_array(
        'sprintf',
        array_merge((array) str_repeat('%c', count($bytes)), $bytes)
       );

CodePad.

Upvotes: 1

mario
mario

Reputation: 145482

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()

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:

$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).

Upvotes: 88

Related Questions