tags:

views:

205

answers:

4

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.

+4  A: 

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:

too much php
A: 

You can read the file with either fread or file_get_contents, then split it with str-split:

$MyArray = str_split($file);
Björn
+1  A: 

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.
Gordon
A: 

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"; }

Mantas
pointless micro-optimization. and your answer should have been a comment below the answer as well.
Gordon
Of all micro optimizations, this one is the least pointless if at all.
Raveren
yes. but in zend sertificate very frequent.
Mantas
@Raveren Even for an array containing the numbers 1 to 1M, using `for` with `count` requires a mere ~0.8s more. For 1-10k, this is already 0.002s only. And for less than that it's hardly measurable.
Gordon
I left out this optimization for the sake of simplicity.
too much php