如何正確使用php的stream_get_contents

PHP
小樊
81
2024-09-20 15:38:30

stream_get_contents 是一個(gè) PHP 函數(shù),用于從給定的流(如文件、字符串或數(shù)據(jù)流)中讀取所有內(nèi)容并將其作為字符串返回

  1. 打開一個(gè)文件用于讀取:
$filename = 'example.txt';
$file = fopen($filename, 'r');
if (!$file) {
    die("Error: Could not open file '$filename'.");
}
  1. 使用 stream_get_contents 從文件中讀取內(nèi)容:
$content = stream_get_contents($file);
if ($content === false) {
    die("Error: Could not read from file '$filename'.");
}
  1. 關(guān)閉文件:
fclose($file);
  1. 處理讀取到的內(nèi)容:
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'.");
}

// 從文件中讀取內(nèi)容
$content = stream_get_contents($file);
if ($content === false) {
    die("Error: Could not read from file '$filename'.");
}

// 關(guān)閉文件
fclose($file);

// 處理讀取到的內(nèi)容
echo "Content of the file '$filename':\n";
echo $content;
?>

對(duì)于其他類型的流(如字符串或數(shù)據(jù)流),只需將 fopen 替換為相應(yīng)的函數(shù)(如 fopen('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==', 'r'))即可。

0