What are some best practices for optimizing the process of exporting data from a PHP recordset to a text file?

When exporting data from a PHP recordset to a text file, it is important to optimize the process to ensure efficiency and accuracy. One best practice is to use a loop to iterate through the recordset and write each row to the text file. Additionally, consider using proper formatting and delimiter characters to make the text file easily readable and parseable.

// Assume $recordset is the PHP recordset containing the data
// Assume $filename is the name of the text file to export to

$fp = fopen($filename, 'w');

if ($fp) {
    while ($row = $recordset->fetch_assoc()) {
        fputcsv($fp, $row, "\t"); // Use tab delimiter for better readability
    }

    fclose($fp);
    echo "Data exported successfully.";
} else {
    echo "Error opening file for writing.";
}