Get part of a file by byte number in php

2020-03-27 10:51发布

How can I have php return just some bytes of a file? Like, it I wanted to load byte 7 through 15 into a string, without reading any other part of the file? Its important that I don't need to load all of the file into memory, as the file could be quite large.

标签: php file
3条回答
闹够了就滚
2楼-- · 2020-03-27 11:06

Using Pear:

<?php
require_once 'File.php';

//read and output first 15 bytes of file myFile
echo File::read("/path/to/myFile", 15);
?>

Or:

<?php
// get contents of a file into a string
$filename = "/path/to/myFile";
$handle = fopen($filename, "r");
$contents = fread($handle, 15);
fclose($handle);
?>

Either method you can use byte 7-15 to do what you want. I don't think you can go after certain bytes without starting from the beginning of the file.

查看更多
Bombasti
3楼-- · 2020-03-27 11:21

Could use file_get_contents() using the offset and maxlen parameters.

$data = file_get_contents('somefile.txt', NULL, NULL, 6, 8);
查看更多
小情绪 Triste *
4楼-- · 2020-03-27 11:23

Use fseek() and 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);
查看更多
登录 后发表回答