PHP Streams函数

PHP stream_get_contents() 函数将流的剩余部分读取到字符串中。此函数与 file_get_contents() 相同,不同之处在于 stream_get_contents() 运行于已打开的stream资源,并以字符串形式返回剩余内容,最多为maxlength个字节,并从指定的偏移量开始。

语法

stream_get_contents(stream, maxlength, offset) 

    参数

    stream必填。 指定流资源,例如从fopen()函数返回。
    maxlength可选。 指定要读取的最大字节数。默认值为 -1(读取所有剩余缓冲区)。
    offset可选。 在读取之前查找指定的偏移量。如果该数字为负数,则不会进行查找,并且将从当前位置开始读取。默认值为 -1。

    返回值

    失败时返回字符串或 false。

    示例:读取文件

    假设我们有一个名为test.txt的文件。该文件包含以下内容:

    This is a test file.
    It contains dummy content. 
    • 1

    在下面的示例中,使用stream_get_contents()函数读取其内容。

    <?php
    $file = "test.txt";
    
    //以读模式打开文件
    $stream = fopen($file, 'r');
    
    //读取并显示文件内容
    echo stream_get_contents($stream);
    
    //关闭流
    fclose($stream);
    ?> 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    输出上面的代码将是:

    This is a test file.
    It contains dummy content. 
    • 1

    示例:读取文件的一部分

    通过使用offsetmaxlength 参数,我们可以指定从哪里开始读取以及读取数据的最大长度。

    <?php
    $file = "test.txt";
    
    //以读模式打开文件
    $stream = fopen($file, 'r');
    
    //读取并显示文件内容
    //最大长度 = 20 且偏移量 = 5
    echo stream_get_contents($stream, 20, 5);
    
    //关闭流
    fclose($stream);
    ?> 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    上述代码的输出将是:

    is a test file.
    It 
    • 1