How to read bz2 file as an array with PHP
There is a function you may know开发者_开发技巧 gzfile which "Read entire gz-file into an array", how can you do the same with bz2? Thanks!
There's no built in function.
You could do something like this (add some sanity checks, etc):
function bzfile($filename){
$p = popen('bunzip2 -c ' . $filename, 'r');
$a = array();
while($a[] = fgets($p);
return $a;
}
This assumes a unix-like os with a bunzip2 binary installed. It runs buznip2 on your file. The -c option means "send uncompressed data to stdout instead of affecting the file on disk). That output behaves like a file handle, so you can fgets on it to read lines.
EDIT: There is an extension that provides some built-in bz2 functionality, though sadly, no bzfile(). If the bzip2 extension is available in your environment, you could rewrite the above like:
function bzfile($file){
$fp = bzopen('foo.bz2','r');
$a = array();
while ($a[] = fgets($fp));
return $a;
}
This will not require a unix environment or installed bunzip2 binary.
(NOTE: this all assumes the bzipped file is text and doesn't contain binary data, since you wanted a replacement for file())
精彩评论