Reading and writing files

Read project files with file_get_contents, file() and fgetcsv; write temporary files under /tmp.

Runs in Zerethon IDE · PHP 8.4 Official PHP documentation ↗
main.php
<?php

$handle = fopen(__DIR__ . '/data.csv', 'r');
fgetcsv($handle, escape: '');                 // skip the header
$names = [];
while (($row = fgetcsv($handle, escape: '')) !== false) {
    $names[] = $row[0];
}
fclose($handle);
echo implode(', ', $names), "\n";

file_put_contents('/tmp/report.json', json_encode(['count' => count($names)]));
$report = json_decode(file_get_contents('/tmp/report.json'), true);
echo $report['count'], "\n";
data.csv
name,score
ada,90
alan,85

Output

ada, alan
2
  • __DIR__ is the folder of the current file — safer than a relative path when files include each other.
  • Project files are read-only: writing next to them fails with Failed to open stream: Read-only file system. Write to /tmp.
  • json_decode($text, true) gives arrays; without true it gives objects.

Related topics

Official references