stream_get_contents
(PHP 5, PHP 7, PHP 8)
stream_get_contents — 读取资源流到一个字符串
说明
与 file_get_contents() 一样,但是
stream_get_contents() 是对一个已经打开的资源流进行操作,并将其内容写入一个字符串返回。
返回的内容取决于 length
字节长度和 offset
指定的起始位置。
参数
返回值
返回一个字符串 或者在失败时返回 false
.
更新日志
版本 | 说明 |
---|---|
8.0.0 |
现在 length 可以为 null。
|
示例
示例 #1 stream_get_contents() 例子
<?php
if ($stream = fopen('http://www.example.com', 'r')) {
// 打印从开始的位置偏移 10 个字节后页面的所有内容
echo stream_get_contents($stream, -1, 10);
fclose($stream);
}
if ($stream = fopen('http://www.example.net', 'r')) {
// 打印前 5 个字节
echo stream_get_contents($stream, 5);
fclose($stream);
}
?>
+添加备注
用户贡献的备注 2 notes
clarck dot smith at gmail dot com ¶
13 years ago
In that case when stream_get_contents/fread/fgets or other stream reading functions block indefinitely your script because they don't reached the limit of bytes to read use the socket_get_meta_data function to figure out the number of the bytes to read. It returns an array that contains a key named 'unread_bytes' and then pass that number to your favourite stream reading functions second parameter to read from the stream.
Maybe a good workaround to use the stream_select function, and set the socket to non-blocking mode with the use of stream_set_blocking($stream, 0). In this case the socket reading functions work properly.
Cheers, Ervin
备份地址:http://www.lvesu.com/blog/php/function.stream-get-contents.php