阅读量:111
stream_get_contents 是 PHP 中一个用于从流中读取数据的函数
- 从文件中读取内容:
$filename = 'example.txt';
$content = stream_get_contents($filename);
echo $content;
- 从 URL 中读取内容:
$url = 'https://example.com/file.txt';
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'User-Agent: Mozilla/5.0 (compatible; My_Example_Bot/1.0; +http://example.com/bot)'
]
]);
$content = stream_get_contents($url, false, $context);
echo $content;
- 从字符串中读取内容:
$string = 'Hello, World!';
$content = stream_get_contents(fopen('[removed]' . base64_encode($string), 'r'));
echo $content;
- 从资源中读取内容:
$resource = fopen('php://memory', 'r');
fwrite($resource, 'Hello, World!');
rewind($resource);
$content = stream_get_contents($resource);
fclose($resource);
echo $content;
在这些示例中,stream_get_contents 函数用于从不同的数据源(文件、URL、字符串和资源)中读取内容。这使得它在处理网络编程和其他需要处理流数据的场景中非常有用。