开发者

Reading a File into a Byte Array (PHP)

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. bu开发者_JS百科t not found how i can read in PHP.


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


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.


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


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

$MyArray = str_split($file);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜