How can one efficiently write data from a database to a file in PHP without exceeding memory limits?

When writing data from a database to a file in PHP, it's important to avoid loading all the data into memory at once to prevent exceeding memory limits. One way to efficiently write data to a file is to fetch rows from the database one at a time and write them to the file immediately, rather than storing them all in an array.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Open a file for writing
$file = fopen('output.txt', 'w');

// Fetch data from the database and write to the file
$stmt = $pdo->query('SELECT * FROM table');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    fwrite($file, implode(',', $row) . PHP_EOL);
}

// Close the file and database connection
fclose($file);
$pdo = null;
?>