我有一个文件,但现在需要将其读入一个字节数组。在Java或C++中,这很容易实现,但是我不知道如何在PHP中读取。
你可以像这样将文件读入字符串:
$data = file_get_contents("/tmp/some_file.txt");
你可以像在C语言中一样访问单个字节:
for($i = 0; $i < strlen($data); ++$i) {
$char = $data[$i];
echo "Byte $i: $char\n";
}
参考资料:
$str[42]
。为此目的,请将字符串视为字符数组。当您想要提取或替换多个字符时,可以使用substr()
和substr_replace()
函数。$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
echo "$char\n";
}
这不是一个字节数组,而是遍历文件句柄。SplFileInfo实现了SeekableIterator接口。
此外,还有一个函数:
太多的php>
$data = file_get_contents("/tmp/some_file.txt");
最好的方法是使用for循环(不推荐使用count、sizeof、strlen或其他函数):$counter = strlen($data);
for($i = 0; $i < $counter; ++$i) {
$char = data[$i];
echo "字节 $i: $char\n";
}
for
和count
仅需要多约0.8秒。对于1-10k,这已经只有0.002秒了。而对于更少的数字,几乎无法测量。 - Gordon
$char = $data[$i];
- Arvind Bhardwaj