如何正确使用php的stream_get_contents

   2024-09-30 7230
核心提示:stream_get_contents 是一个 PHP 函数,用于从给定的流(如文件、字符串或数据流)中读取所有内容并将其作为字符串返回打开一个

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'))即可。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号