Current Location: Home> Function Categories> stream_get_contents

stream_get_contents

Read resource stream to a string
Name:stream_get_contents
Category:Stream
Programming Language:php
One-line Description:Read the content of the resource stream and can be used to read various types of resources such as files and network streams.

Function name: stream_get_contents()

Function Description: The stream_get_contents() function reads data of a specified length from the resource stream.

Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7

Syntax: stream_get_contents(resource $handle, int $length = -1, int $offset = -1) : string|false

parameter:

  • $handle: Required. A valid resource flow handle.
  • $length: optional. The maximum number of bytes to read. The default is -1, which means that it is read to the end of the file.
  • $offset: optional. The number of bytes offset from the start position of the stream. The default is -1, indicating that reading starts from the current position.

Return value:

  • Returns data read from the resource stream, and returns false if read failed.

Example:

 // 创建一个文件资源流句柄$handle = fopen('data.txt', 'r'); // 读取整个文件内容$content = stream_get_contents($handle); echo $content; // 读取文件的前100个字节$content = stream_get_contents($handle, 100); echo $content; // 从文件的第200个字节开始,读取100个字节的内容$content = stream_get_contents($handle, 100, 200); echo $content; // 关闭资源流句柄fclose($handle);

In the above example, we first open a file resource stream handle through the fopen() function. Then, we use the stream_get_contents() function to read the contents of the file. In the first example, we do not specify the length and offset, so the function reads the contents of the entire file. In the second example, we specify that the length is 100, and the function reads the first 100 bytes of the file. In the third example, we specify a length of 100 and an offset of 200, and the function reads 100 bytes from the 200th byte of the file. Finally, we closed the resource flow handle through the fclose() function.

Please note that the stream_get_contents() function is used to read the content of a resource stream and can be used to read various types of resources such as files and network streams.

Similar Functions
Popular Articles