Page 1 of 1

How to read/convert a file into a byte array?

Posted: Fri Jan 20, 2006 2:40 am
by mlorenz
I've done my best to find something that clearly describes how read a file into a byte array, but I'm still missing something, after hours of trying. Specifically, I'm uploading an image file to one server, then I need to read that file into a byte array so I can make a method call which takes the byte array as input. I start with:

Code: Select all

$dataString = file_get_contents( $uploadedFile );
and pass $dataString to variations of:

Code: Select all

function asc2bin ($temp) {
  $data = array();
  $len = strlen($temp);
  for ($i=0; $i<$len; $i++) 
      $data[$i]=sprintf( "%08b", ord( substr( $temp, $i, 1 ) ) );
  return $data;
}
I've also looked at using pack/unpack, but I haven't been able to figure them out yet.

I've been banging my head against a wall here, and I suspect that there's a really easy way to do this that I'm missing. If someone out there has done this, or knows how, I would *really* appreciate the help!

Posted: Fri Jan 20, 2006 8:05 am
by feyd
the returned "string" from file_get_contents() is a byte array. :? It appears you want to transform the binary string into an integer array. Semantics, I know, but it is important in php because of the typeless systems..

Code: Select all

function string2intArr($string) {
  $l = strlen($string);
  $r = array();
  for($i = 0; $i < $l; $i+) {
    $r[] = ord($string{$i});
  }
  return $r;
}
that's untested.

How to read/convert a file into a byte array?

Posted: Fri Jan 20, 2006 5:57 pm
by mlorenz
Feyd,

Thanks for the response. I've tried file_get_contents, the code you supplied (with a minor correction from "i+" to "i++" to get it working), fread, etc. Sometimes I get: "soapenv:Server.userException: org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x0) was found in the element content of the document". Other times there's no error message, but the data on the server is definitely incorrect.

It seems that even if the returned string really is a byte array, SOAP still doesn't like it. Everything else I've needed to do with PHP has been fine, but this very important piece just isn't - and it's absolutely necessary that I get this bit figured out, too. As one would expect. ;-)

Posted: Fri Jan 20, 2006 6:02 pm
by feyd
are you sure the file you've uploaded, uploaded correctly? The error put out appears to say there's a null byte (0) somewhere in the file.