0Pricing
PHP Academy · 课时

使用 PHP 读取文件

使用 file_get_contents 和 fopen/fread 读取文件内容。

使用 PHP 读取文件 是 CoddyKit 上的免费 PHP Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PHP Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PHP Academy 课程共包含 4 节课。

PHP 与文件系统

PHP 可以在服务器的文件系统上读取、写入和管理文件。用于读取的主要函数包括:

  • file_get_contents() — 将整个文件读取为字符串
  • fopen() + fread() — 基于流的读取
  • file() — 将文件读取为行数组

file_get_contents()

将文件的全部内容读取为字符串的最简单方法:

<?php
$content = file_get_contents('/var/www/html/data.txt');

if ($content === false) {
    echo 'Could not read file';
} else {
    echo $content;
    echo strlen($content) . ' bytes';
}

检查文件是否存在

读取前始终进行检查,以避免错误:

<?php
$path = '/var/data/config.json';

if (!file_exists($path)) {
    die('Config file not found');
}

if (!is_readable($path)) {
    die('No permission to read file');
}

$json = file_get_contents($path);
$config = json_decode($json, true);

file() — 读取到数组

file() 会读取文件,并将每一行作为数组元素返回:

<?php
$lines = file('data.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($lines as $lineNum => $line) {
    echo ($lineNum + 1) . ': ' . $line . PHP_EOL;
}

fopen、fread、fclose

适用于大文件的底层流读取——无需将全部内容加载到内存中即可进行处理:

<?php
$handle = fopen('large_file.txt', 'r');

if ($handle === false) die('Cannot open file');

// Read 1KB at a time
while (!feof($handle)) {
    $chunk = fread($handle, 1024);
    echo $chunk;
}

fclose($handle);

使用 fgets 逐行读取

fgets() 一次读取一行——处理大文件时可以节省内存:

<?php
$handle = fopen('server.log', 'r');

while (($line = fgets($handle)) !== false) {
    if (str_contains($line, 'ERROR')) {
        echo 'Found error: ' . $line;
    }
}

fclose($handle);

读取远程文件

如果启用了 allow_url_fopen,file_get_contents() 也可以从 HTTP URL 读取内容:

<?php
$json = file_get_contents('https://api.example.com/data.json');

// Prefer cURL for more control and error handling
$ch = curl_init('https://api.example.com/data.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

SplFileObject

SplFileObject 为文件操作提供 OO 接口:

<?php
$file = new SplFileObject('data.txt', 'r');

foreach ($file as $lineNum => $line) {
    echo $lineNum . ': ' . $line;
}

// Read specific line:
$file->seek(5);
echo $file->current(); // line 6 (0-indexed)

读取 JSON 文件

一种常见模式:读取并解码 JSON 配置文件:

<?php
function loadJsonConfig(string $path): array {
    if (!file_exists($path)) {
        throw new RuntimeException("Config not found: $path");
    }
    $json = file_get_contents($path);
    $data = json_decode($json, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new RuntimeException('Invalid JSON: ' . json_last_error_msg());
    }
    return $data;
}

$cfg = loadJsonConfig('/app/config.json');

文件信息

无需读取文件内容即可获取文件的元数据:

<?php
$path = '/var/www/html/image.jpg';

echo filesize($path);           // bytes
echo filetype($path);           // 'file'
echo filemtime($path);          // last modified timestamp
echo date('Y-m-d', filemtime($path));

$info = pathinfo($path);
echo $info['dirname'];    // /var/www/html
echo $info['basename'];   // image.jpg
echo $info['extension'];  // jpg

锁定文件

使用文件锁定来防止并发写入冲突:

<?php
$handle = fopen('counter.txt', 'r+');

if (flock($handle, LOCK_EX)) {  // exclusive lock
    $count = (int) fread($handle, 20);
    $count++;
    fseek($handle, 0);
    fwrite($handle, $count);
    fflush($handle);
    flock($handle, LOCK_UN);    // release
}

fclose($handle);

快速检查

哪个 PHP 函数可以通过一次调用将整个文件读取为字符串?

回顾:读取文件

读取文件的基础知识:

  • file_get_contents() — 将整个文件读取为字符串
  • file() — 将文件读取为行数组
  • fopen/fread/fclose — 用于大文件的流
  • fgets() — 逐行读取流
  • 始终先检查 file_exists 和 is_readable
  • 使用 flock 确保并发访问安全

常见问题解答

「使用 PHP 读取文件」课时是免费的吗?

是的 — 「使用 PHP 读取文件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PHP Academy 课程的其余内容,请升级到 CoddyKit PRO。 PHP Academy 课程共包含 4 节课。

「使用 PHP 读取文件」这节课中我会学到什么?

使用 file_get_contents 和 fopen/fread 读取文件内容。 你通过在浏览器中直接运行的动手代码来练习 PHP Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 PHP Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 PHP Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 PHP 读取文件」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 PHP Academy 课中编写并运行代码吗?

能。每节 PHP Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 PHP 读取文件
  2. 写入和追加文件内容
  3. 操作目录
  4. 处理文件上传
← 返回 PHP Academy