Skip to content
PHP

在 PHP 中读写文件

使用 PHP 文件系统函数读取、写入、追加和遍历文件。

#file#io#intermediate

Code

php
<?php

// Read entire file
$content = file_get_contents("data.txt");
echo $content;

// Read lines into array
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);

// Write file
file_put_contents("output.txt", "Hello\n");

// Append
file_put_contents("log.txt", "New entry\n", FILE_APPEND);

// Open / read / close
$handle = fopen("data.txt", "r");
while (($line = fgets($handle)) !== false) {
    echo trim($line);
}
fclose($handle);

// Check file
if (file_exists("data.txt")) {
    echo filesize("data.txt");
}

// Directory listing
foreach (glob("*.txt") as $file) {
    echo $file;
}