Link to home
Start Free TrialLog in
Avatar of Lasitha
Lasitha

asked on

Convert file into byte array

How to convert file content into byte array using php?

$content = file_get_contents($file['uri']);
$byteArr = unpack("N*", $content);

this didn't work for me.
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Try with explode() method like this:
$content = file_get_contents($file['uri']);
$arr=explode(" ",$content);
foreach ($arr as $value) {
    print_r(unpack("N*",$value));
}

Open in new window

What do you want to do with the file data?
When you read the file in using file_get_contents you get a string which can be accessed like this

$content = file_get_contents($file['uri']);
for($i = 0; $i < strlen($content); $i++) {
  echo $content[$i] . "<br>";
}

Open in new window

I think if you look at the PHP man page http://php.net/manual/en/function.unpack.php , you will see that 'unpack' is not what you want to do.  All files that are not otherwise processed are 'byte arrays' that can be accessed like Julian shows above with a numerical index.  'Real' arrays in PHP have two parts, the Key and the Value.  That will make your array at least twice the size it needs to be.

Like Julian asked, what do you want to do with it?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.