How to write the data into a csv file?

How to write the data into a csv file?

August 4, 2026 · Illustrated author avatarBy Stefan Bogdanescu
How to write the data into a csv file?

Writing Data into a CSV File: A Comprehensive Guide

Exporting data from your application to a CSV (Comma Separated Values) file is a common requirement for sharing or processing data outside the system. However, working with CSV files requires a different approach compared to traditional database operations.

Understanding the Current Code Structure

Let’s first understand what your current code aims to achieve:

foreach ($collection as $product_all)
{
    // Extracting product details using Magento API
    // ...

    // Attempting to read and manipulate the CSV file
    if (($handle = fopen("test.csv", "r")) !== FALSE) 
    {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
        {
            $data[0] = $sku;
            $data[2] = $name;
            $newCsvData[] = $data;
        }
        fclose($handle);
    }

    // Writing the updated data back to the CSV file
    $handle = fopen('test.csv', 'w');
    foreach ($newCsvData as $line)
    {
        fputcsv($handle, $line);
    }

    fclose($handle);
}

This script is trying to read an existing test.csv file, update specific values for each product in the collection, and then rewrite the entire file with the updated data. However, this approach has some significant issues.

The Problems with the Current Approach

  1. Performance Issues: Reading and rewriting a CSV file line by line is inefficient, especially if you’re dealing with large datasets like 8000 rows. This can lead to heavy disk I/O operations, slowing down your script’s performance.

  2. Data Loss Risk: If an error occurs while writing the data back to the file (like running out of disk space), you risk losing all the updated data since it wasn’t persisted between each loop iteration.

  3. Inaccurate Updates: The code attempts to update specific columns by index, which can lead to incorrect updates if your CSV structure changes (e.g., adding or removing columns).

A More Efficient Approach

To overcome these challenges, you should adopt a different strategy:

  1. Open the File Once and Keep It Open: Instead of opening and closing the file in every loop iteration, open it once at the beginning and keep it open until all updates are complete.

  2. Use Stream Wrappers for Easier Handling: PHP offers stream wrappers like file:// which can simplify file operations compared to the low-level fopen() function.

  3. Update Data in Memory Before Writing Back: Rather than updating the CSV data directly, store the updated values in an array and write them back only after all updates are complete.

Here’s a sample implementation of this approach:

$handle = fopen('test.csv', 'r+'); // Open file for reading and writing

if ($handle === FALSE) {
    die("Could not open file");
}

$newCsvData = array();
while (($data = fgetcsv($handle)) !== FALSE)
{
    $sku = $data[0];  // Assuming the first column is SKU
    if ($sku == $product_all['sku']) {  // Find matching row
        // Update values in memory
        $newCsvData[] = array($product_all['sku'], $product_all['name']);
    } else {
        $newCsvData[] = $data;  // Keep original data if no match
    }
}

fclose($handle); // Close the file

$handle = fopen('test.csv', 'w'); // Reopen for writing
foreach ($newCsvData as $line)
{
    fputcsv($handle, $line);
}
fclose($handle);

Conclusion

Exporting data to a CSV file requires careful handling to ensure efficient performance and accurate results. By understanding the limitations of your current approach and adopting best practices like keeping the file open and updating data in memory before writing back, you can create a more robust and performant solution.

Remember that working with external files always carries risks, so ensure you have proper error handling and backup mechanisms in place.

For more advanced CSV operations and performance optimization techniques, consider exploring libraries like PHP-Excel or CSVReader. You can also learn more about file I/O best practices in the official PHP documentation: https://www.php.net/manual/en/filehandling.php

Catalog Database Performance API

Our network