Im writing a PHP script to run in apache2. I'm getting a byte array from a device that I need to parse into an object. When I do a $body = file_get_contents('php://input'), I get a string. Then I need to do a funky unpack('C*', $body). Now I have an array that has an extra element in the beginning, from the unpack process. It seems I'm trying too hard to do something that seems trivial.
Is there a way to just read the body as a byte array, and skip all the string conversion garbage? Come on PHP! Its just an array of bytes!
Trust me, believe or not there are no specific byte containers in PHP. You are doing it in the correct way. I have developed several binary algorithms in this language, it's really hard to understand when you come from other languages like C++ or Delphi.
In PHP the standard byte array container is the string. For example:
$myVar = file_get_contents("/folder/myfile.bin");
In this case myVar acts as string and also as array of bytes.
The only way to change bytes representation is performing pack and unpack operations.
$myByteArray= unpack("N*",$myvar);
for($i = 0; $i < strlen($myByteArray); $i++)
{
echo $myByteArray[$i].'<br/>';
}
Here you have some good explanations:
http://docstore.mik.ua/orelly/webprog/pcook/ch01_14.htm
http://www.codediesel.com/php/unpacking-binary-data/
And let me give you a last tip based on my experience: if you plan to migrate your PHP application to many different hardware arquitectures, take care of endianess on pack/unpack operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With