【问题标题】:Get part of a file by byte number in php在php中按字节数获取文件的一部分
【发布时间】:2011-06-30 02:35:34
【问题描述】:

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

【问题讨论】:

    标签: php file


    【解决方案1】:

    可以通过 offset 和 maxlen 参数使用file_get_contents()

    $data = file_get_contents('somefile.txt', false, NULL, 6, 8);
    

    【讨论】:

    • 如果我没记错的话,第二个参数应该是false 而不是null
    【解决方案2】:

    使用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);
    

    【讨论】:

    • 啊哈...我打算使用fread()str_split() 发布一个稍微笨拙的答案。完全忽略了fseek()。这要简洁得多。谢谢,以后一定要记住!
    • 如果您使用的是 Windows,请不要忘记帮助部分中的注释:在区分二进制文件和文本文件的系统(即 Windows)上,必须使用 fopen 中包含的 'b' 打开文件() 模式参数。 (所以fopen('somefile.txt', 'rb')
    【解决方案3】:

    使用梨:

    <?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 来做您想做的事。我认为如果不从文件的开头开始,你就不能追踪某些字节。

    【讨论】:

      猜你喜欢
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多