1) Set appropriate PHP configuration: Adjust the PHP configuration settings to handle large datasets. Modify the following settings in your php.ini file or within your PHP script:
2) Open and write to the CSV file: Open a file handle using fopen to create the CSV file and use fwrite or fputcsv to write data to the file. It's recommended to use the fputcsv function as it automatically handles special characters and formatting. And use flush and buffer data: To avoid memory issues when exporting large datasets, periodically flush and buffer the data to disk. This ensures that the data is written to the file and cleared from memory. Here's an example of flushing the buffer after writing a certain number of rows:
Or you can use my sample code below: