在php中按字节数获取文件的一部分

Joh*_*mac 2 php file

我怎么能让PHP返回文件的一些字节?就像,我想将字节7到15加载到字符串中,而不读取文件的任何其他部分?重要的是我不需要将所有文件加载到内存中,因为文件可能非常大.

小智 13

可以使用offset和maxlen参数来使用file_get_contents().

$data = file_get_contents('somefile.txt', NULL, NULL, 6, 8);
Run Code Online (Sandbox Code Playgroud)


Yan*_*hon 10

使用fseek()fread()

$fp = fopen('somefile.txt', 'r');

// move to the 7th byte
fseek($fp, 7);

$data = fread($fp, 8);   // read 8 bytes from byte 7

fclose($fp);
Run Code Online (Sandbox Code Playgroud)