File Input & Output
⏱ 20 min read read
Quick File Functions (Most Common):
// Write entire file at once
file_put_contents('notes.txt', "Hello!\nLine 2\n");
// Read entire file at once
$content = file_get_contents('notes.txt');
// Read into array of lines
$lines = file('notes.txt', FILE_IGNORE_NEW_LINES);
// Check if file exists
file_exists('notes.txt'); // true or false
fopen / fclose (Stream API):
// Modes: r=read, w=write(overwrite), a=append, x=create(fail if
exists)
$handle = fopen('notes.txt', 'w');
fwrite($handle, "Hello!\n");
fclose($handle);
// Reading line by line
$handle = fopen('notes.txt', 'r');
while (($line = fgets($handle)) !== false) {
echo trim($line) . "\n";
}
fclose($handle);
CSV Files:
// Write CSV
$handle = fopen('grades.csv', 'w');
fputcsv($handle, ['Name', 'Grade']); // header
fputcsv($handle, ['Alice', 92]);
fclose($handle);
// Read CSV
$handle = fopen('grades.csv', 'r');
$header = fgetcsv($handle); // read header row
while (($row = fgetcsv($handle)) !== false) {
[$name, $grade] = $row;
echo "$name: $grade\n";
}
fclose($handle);
JSON Files:
// Write JSON
$data = ['name' => 'Alice', 'age' => 25, 'scores' =>
[92, 85, 88]];
file_put_contents('data.json', json_encode($data,
JSON_PRETTY_PRINT));
// Read JSON
$loaded = json_decode(file_get_contents('data.json'), true); //
true = assoc array
echo $loaded['name'] . "\n";
// Write entire file at once
file_put_contents('notes.txt', "Hello!\nLine 2\n");
// Read entire file at once
$content = file_get_contents('notes.txt');
// Read into array of lines
$lines = file('notes.txt', FILE_IGNORE_NEW_LINES);
// Check if file exists
file_exists('notes.txt'); // true or false
fopen / fclose (Stream API):
// Modes: r=read, w=write(overwrite), a=append, x=create(fail if
exists)
$handle = fopen('notes.txt', 'w');
fwrite($handle, "Hello!\n");
fclose($handle);
// Reading line by line
$handle = fopen('notes.txt', 'r');
while (($line = fgets($handle)) !== false) {
echo trim($line) . "\n";
}
fclose($handle);
CSV Files:
// Write CSV
$handle = fopen('grades.csv', 'w');
fputcsv($handle, ['Name', 'Grade']); // header
fputcsv($handle, ['Alice', 92]);
fclose($handle);
// Read CSV
$handle = fopen('grades.csv', 'r');
$header = fgetcsv($handle); // read header row
while (($row = fgetcsv($handle)) !== false) {
[$name, $grade] = $row;
echo "$name: $grade\n";
}
fclose($handle);
JSON Files:
// Write JSON
$data = ['name' => 'Alice', 'age' => 25, 'scores' =>
[92, 85, 88]];
file_put_contents('data.json', json_encode($data,
JSON_PRETTY_PRINT));
// Read JSON
$loaded = json_decode(file_get_contents('data.json'), true); //
true = assoc array
echo $loaded['name'] . "\n";
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress