Reading a file into an array of bytes (PHP)

I have one file. but now you need to read this file in an array of bytes. In java or C ++ this is very easy to do. but did not find how I can read in PHP.

+6
php streaming
source share
4 answers

You can read the file in a line like this:

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

You can get individual bytes similar to what you would in C:

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

Literature:

+10
source share

See PHP Guide for Accessing and Modifying a String by Character

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

Or, if you are after searching and reading bytes from a file, you can use SplFileObject

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

This is not a byte array, but, but repeated over the file descriptor. SplFileInfo implements the SeekableIterator interface.

And on the sidebar there is also

  • file - returns a file in an array. Each element of the array corresponds to a line in the file, and a new line is still attached. After the failure, the file () returns FALSE.
+4
source share

You can read the file using fread() or file_get_contents() , then split it into str_split() :

 $MyArray = str_split($file); 
+2
source share

too much php>

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

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

+2
source share

All Articles