Is there some PHP function or class that allows me to read a file like an array of characters?
For example:
$string = str_split('blabla');
$i = 0;
switch($string[$i]){
case 'x':
do_something();
$i++;
case 'y':
if(isset($string[++$i]))
do_something_else();
else
break;
case 'z':
// recursive call of this code etc..
}
I know that I can use $string = file_get_contents($file), but the problem is that I get a huge amount of memory used for a tiny 800K file (like 80MB).
So can I somehow “stream” the file in my code above with some kind of arrayaccess like class that automatically reads data from the file when I call isset() ? 🙂
You can use
fseekandfgetcto jump around in a file and read single characters at a time.You mentioned you wanted array behavior specifically. You can build a class which implements
ArrayAccessto support this.This could be dangerous for several reasons:
$charinputs that request indices past the length of the fileA slightly more efficient alternative would be to “lazily” read the file (i.e., read it in chunks rather than all at once). Here’s some (untested) code: