PHP:
阅读文本文件

How to: (如何操作)

<?php
// 读取整个文件到一个字符串
$content = file_get_contents("example.txt");
echo $content;

// 逐行读取文件
$file = new SplFileObject("example.txt");
while (!$file->eof()) {
    echo $file->fgets();
}

// 使用file()函数读取文件到数组每行一项
$lines = file("example.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
    echo $line . PHP_EOL;
}
?>

输出取决于"example.txt"的内容。

Deep Dive (深度剖析)

以前,我们可能使用fopen(), fgets(), 和fclose()实现文件读取。现在,除了file_get_contents()file(),还可以用SplFileObject,它提供了面向对象的文件操作方法。

同样重要的是处理异常-文件可能不存在或读取错误。PHP提供try...catch结构以优雅地处理这些情况。

<?php
try {
    $content = file_get_contents("missing.txt");
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

替代方法:在Linux系统中,也可以使用命令行工具如cat通过exec()读取文件,但在Web应用中通常不推荐。

See Also (另请参阅)