[php] String to byte array in php

How can I get the byte array from some string which can contain numbers, letters and so on? If you are familiar with Java, I am looking for the same functionality of the getBytes() method.

I tried a snippet like this one:

for($i = 0; $i < strlen($msg); $i++){
    $data.=ord($msg[$i]);
        //or $data[]=ord($msg[$1]); 
}

but without success, so any kind of help will be appreciated.

PS: Why do I need this at all!? Well, I need to send a byte array via fputs() to a server written in Java...

This question is related to php bytearray

The answer is


print_r(unpack("H*","The quick fox jumped over the lazy brown dog"))

Array ( [1] => 54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67 ) 

T = 0x54, h = 0x68, ...

You can split the result into two-hex-character chunks if necessary.


I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.

Take byteStr2byteArray() as an example:

<?php
function byteStr2byteArray($s) {
    return array_slice(unpack("C*", "\0".$s), 1);
}

$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);

for($i=0;$i<count($byte_array);$i++)
{
   printf("0x%02x ", $byte_array[$i]);
}
?>

In PHP, strings are bytestreams. What exactly are you trying to do?

Re: edit

Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...

fputs takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).


PHP has no explicit byte type, but its string is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …"). The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.


You could try this:

$in_str = 'this is a test';
$hex_ary = array();
foreach (str_split($in_str) as $chr) {
    $hex_ary[] = sprintf("%02X", ord($chr));
}
echo implode(' ',$hex_ary);