我怎样才能让php返回文件的某些字节?就像,我想将字节7到15加载到字符串中,而不读取文件的任何其他部分?重要的是我不需要将所有文件加载到内存中,因为文件可能非常大。
答案 0 :(得分:12)
可以使用file_get_contents()使用offset和maxlen参数。
$data = file_get_contents('somefile.txt', NULL, NULL, 6, 8);
答案 1 :(得分:10)
$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);
答案 2 :(得分:1)
使用Pear:
<?php
require_once 'File.php';
//read and output first 15 bytes of file myFile
echo File::read("/path/to/myFile", 15);
?>
或者:
<?php
// get contents of a file into a string
$filename = "/path/to/myFile";
$handle = fopen($filename, "r");
$contents = fread($handle, 15);
fclose($handle);
?>
无论哪种方法,您都可以使用字节7-15来执行您想要的操作。我不认为你可以在不从文件开头开始的情况下追踪某些字节。