2
我有一个PHP的大文件,我想用其他一些512字节替换前512个字节。有什么PHP函数可以帮助我吗?如何更改文件的前512个字节?
我有一个PHP的大文件,我想用其他一些512字节替换前512个字节。有什么PHP函数可以帮助我吗?如何更改文件的前512个字节?
如果要选择创建一个文件并读取和写入(但不截断它),你需要打开与fopen()
功能在文件中'c+'
模式:然后
$handle = fopen($filename, 'c+');
PHP有stream_get_contents()
功能,其允许读取的字节的块具有特定长度(和从特定文件中的偏移)到字符串变量:
$buffer = stream_get_contents($handle, $length = 512, $offset = 0);
然而,没有写stream_put_contents()
功能字符串缓冲返回到特定位置/偏移处的流。一个相关的函数是file_put_contents()
,但它不允许以特定偏移量写入文件句柄资源。但有fseek()
和fwrite()
做到这一点:
$bytes_written = false;
if (0 === fseek($handle, $offset)) {
$bytes_written = fwrite($handle, $buffer, $length);
}
以下是完整的画面:
$handle = fopen($filename, 'c+');
$buffer = stream_get_contents($handle, $length = 512, $offset = 0);
// ... change $buffer ...
$bytes_written = false;
if (0 === fseek($handle, $offset)) {
$bytes_written = fwrite($handle, $buffer, $length);
}
fclose($handle);
如果$buffer
长度是不固定的,这将无法正常工作。在这种情况下,最好用两个文件的工作,并使用stream_copy_to_stream()
作为How to update csv column names with database table header概述,或者如果文件不是很大,也可以做,在内存:
$buffer = file_get_contents($filename);
// ... change $buffer ...
file_put_contents($filename, $buffer);