Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a File into a Byte Array (PHP)

Tags:

php

streaming

I have one file. but now need to read this file into a bytes array. In java or c++ it's very easy to do that. but not found how i can read in PHP.

like image 248
Valdas Avatar asked Apr 12 '10 06:04

Valdas


3 Answers

You can read the file into a string like this:

$data = file_get_contents("/tmp/some_file.txt");

You can get at the individual bytes similar to how you would in C:

for($i = 0; $i < strlen($data); ++$i) {
    $char = $data[$i];
    echo "Byte $i: $char\n";
}

References:

  • http://php.net/file_get_contents
  • http://php.net/manual/en/language.types.string.php#language.types.string.substr
like image 182
too much php Avatar answered Nov 03 '22 15:11

too much php


See the PHP Manual on String access and modification by character

Characters within string s may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Or, if you are after seeking and reading bytes from the file, you can use an SplFileObject

$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
    echo "$char\n";
}

That's not a byte array though, but iterating over a file handle. SplFileInfo implements the SeekableIterator Interface.

And on a sidenote, there is also

  • file — Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.
like image 4
Gordon Avatar answered Nov 03 '22 14:11

Gordon


too much php>

$data = file_get_contents("/tmp/some_file.txt");

best way to make for (not recomended in for use count, sizeof, strlen or other functions): $counter = strlen($data); for($i = 0; $i < $counter; ++$i) { $char = data[$i]; echo "Byte $i: $char\n"; }

like image 2
Mantas Avatar answered Nov 03 '22 14:11

Mantas