stream_get_contents

(PHP 5, PHP 7, PHP 8)

stream_get_contents讀取資源流到一個字符串

說明

stream_get_contents(resource $stream, ?int $length = null, int $offset = -1): string|false

file_get_contents() 一樣,但是 stream_get_contents() 是對一個已經打開的資源流進行操作,并將其內容寫入一個字符串返回。 返回的內容取決于 length 字節(jié)長度和 offset 指定的起始位置。

參數

stream (resource)

一個資源流(例如 fopen() 操作之后返回的結果)

length (int)

需要讀取的最大的字節(jié)數。默認為 null(讀取全部的緩沖數據)。

offset (int)

在讀取數據之前先查找指定的偏移量。如果這個數字是負數,就不進行查找,直接從當前位置開始讀取。

返回值

返回一個字符串 或者在失敗時返回 false.

更新日志

版本 說明
8.0.0 現在 length 可以為 null。

范例

示例 #1 stream_get_contents() 例子

<?php

if ($stream fopen('http://www.example.com''r')) {
    
// print all the page starting at the offset 10
    
echo stream_get_contents($stream, -110);

    
fclose($stream);
}


if (
$stream fopen('http://www.example.net''r')) {
    
// print the first 5 bytes
    
echo stream_get_contents($stream5);

    
fclose($stream);
}

?>

注釋

注意: 此函數可安全用于二進制對象。

參見

  • fgets() - 從文件指針中讀取一行
  • fread() - 讀取文件(可安全用于二進制文件)
  • fpassthru() - 輸出文件指針處的所有剩余數據