如何设置PHP中stream_get_line的文件读取起始位置?
问题:从上传文件的指定字符串位置开始读取内容
我通过curl命令 curl -F 'file@logbackup-infitarif' https://mylink 上传文件,使用PHP读取该文件时,当前代码会从文件开头读取到“speedup”位置,但我希望从语句“total size is”处开始读取。
我的PHP代码如下:
<?php // print_r($_FILES); print_r($_FILES["file"]); $file = fopen($_FILES["file"]["tmp_name"], 'r'); print_r($file); var_dump(get_resource_type($file)); print(stream_get_line($file, $lengh, $ending = "speedup")); ?>
待读取的文件内容:
logbackup-final.txt logbackup-final.txt 0000777 0002002 0000144 00000000331 14303633743 013533 0 ustar stag users 2022-08-30 receiving incremental file list 2022/08/30 16:09:56|test/ 2022/08/30 16:09:56|test/DiskStation214_20220622.dss sent 47 bytes received 11,370 bytes 7,611.33 bytes/sec total size is 15,402 speedup is 1.35
解决方案
方法1:逐行扫描定位目标字符串
逐行读取文件,直到找到包含“total size is”的行,再读取该行及后续内容,适合大文件场景:
<?php $tmpFile = $_FILES["file"]["tmp_name"]; $fileHandle = fopen($tmpFile, 'r'); if ($fileHandle) { // 逐行扫描直到匹配目标字符串 while (($line = fgets($fileHandle)) !== false) { // PHP 8.0+用str_contains,低版本替换为strpos($line, 'total size is') !== false if (str_contains($line, 'total size is')) { echo $line; // 读取剩余所有内容 while (($remainingLine = fgets($fileHandle)) !== false) { echo $remainingLine; } break; } } fclose($fileHandle); } ?>
方法2:一次性读取后截取内容
适合小文件,一次性读取全部内容后截取目标位置开始的部分:
<?php $tmpFile = $_FILES["file"]["tmp_name"]; $content = file_get_contents($tmpFile); $target = 'total size is'; $startPos = strpos($content, $target); if ($startPos !== false) { echo substr($content, $startPos); } else { echo '未找到目标字符串'; } ?>
方法3:文件指针定位读取
先获取文件内容找到目标位置,再移动文件指针到该位置后读取:
<?php $tmpFile = $_FILES["file"]["tmp_name"]; $fileHandle = fopen($tmpFile, 'r'); if ($fileHandle) { $fullContent = stream_get_contents($fileHandle); rewind($fileHandle); // 重置指针到文件开头 $target = 'total size is'; $startPos = strpos($fullContent, $target); if ($startPos !== false) { fseek($fileHandle, $startPos); echo stream_get_contents($fileHandle); } fclose($fileHandle); } ?>
内容的提问来源于stack exchange,提问作者Noah Dep
相关产品推荐
相关产品推荐

