stream_get_contents 是一个 PHP 函数,用于从给定的流(如文件、字符串或数据流)中读取所有内容并将其作为字符串返回
$filename = 'example.txt';$file = fopen($filename, 'r');if (!$file) { die("Error: Could not open file '$filename'.");}使用 stream_get_contents 从文件中读取内容:$content = stream_get_contents($file);if ($content === false) { die("Error: Could not read from file '$filename'.");}关闭文件:fclose($file);处理读取到的内容:echo "Content of the file '$filename':\n";echo $content;将以上代码片段组合在一起,完整的示例代码如下:
<?php$filename = 'example.txt';// 打开文件$file = fopen($filename, 'r');if (!$file) { die("Error: Could not open file '$filename'.");}// 从文件中读取内容$content = stream_get_contents($file);if ($content === false) { die("Error: Could not read from file '$filename'.");}// 关闭文件fclose($file);// 处理读取到的内容echo "Content of the file '$filename':\n";echo $content;?>对于其他类型的流(如字符串或数据流),只需将 fopen 替换为相应的函数(如 fopen('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==', 'r'))即可。