PHP - parse a csv file and write output to another csv file

PHP - parse a csv file and write output to another csv file

October 8, 2026 · Illustrated author avatarBy Stefan Bogdanescu
PHP - parse a csv file and write output to another csv file

Parsing and Manipulating CSV Files in PHP: A Comprehensive Guide

Introduction

Working with CSV files is an essential part of data management in many web applications, especially when dealing with large datasets or integrating with external systems like Magento. In this post, we’ll explore how to parse a given CSV file containing product information and output specific rows into new CSV files based on certain conditions.

The Problem: Outputting Each Color Variation as a Separate Row

Let’s take the provided example where we have a CSV file named product.csv with the following content:

Name, description, Color
t-shirt, tshirt description, "green, blue, yellow"

We want to create a new CSV file called new_products.csv, where each row represents a different color variation for the same product. The desired output should look like this:

Name, description, Color
t-shirt, tshirt description, green
t-shirt, tshirt description, blue
t-shirt, tshirt description, yellow

Analyzing the Current Approach

The provided code attempts to read the CSV file line by line and process each field. The main issue lies in how the color variations are being handled within the nested loop:

for ($c=0; $c < $num; $c++) {
    // ...

    if($c == 2){ //if we are at color field
        $color = explode(',', $data[$c]);
        $color_count = count($color);
        for($i=0; $i<=$color_count; $i++){
            fputcsv($fp, array($name,$desc,$color[$i]));
        }
    }
}

The problem arises when we try to open the file handle inside the inner loop. Since fopen creates a new file pointer for each iteration, it overwrites the contents of the output file every time it’s called.

The Solution: Opening the Output File Once

To resolve this issue, we need to move the file opening operation outside the outer loop that iterates through rows:

$fp = fopen('new_products.csv', 'w');
if (!$fp) {
    die("Unable to open output file");
}

if (($handle = fopen("product.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $name = $data[0];
        $desc = $data[1];

        for ($c=2; $c < $num; $c++) { // Start from the third column (Color)
            if($c == 2){
                $color = explode(',', $data[$c]);
                foreach ($color as $single_color) {
                    fputcsv($fp, array($name,$desc,trim($single_color)));
                }
            }
        }
    }
}
fclose($handle);
fclose($fp);

Key Improvements Made

  1. Moved the fopen call for the output file outside all loops to maintain a single persistent file handle.
  2. Changed the starting index of the inner loop from 0 to 2, as we’re only interested in processing the “Color” field (column #3).
  3. Used a foreach loop with a single color item at a time for proper formatting and trimming.

Conclusion

Working with CSV files in PHP can be straightforward once you understand how to handle file pointers and loops correctly. By identifying the issue with opening multiple file handles inside nested loops, we were able to create an optimized solution that outputs each product variation as a separate row in the new CSV file.

Remember, always open your output file before starting any writing operations and close it after finishing to ensure all data is written accurately. For more advanced examples and best practices when working with PHP and CSV files, consider visiting our website at https://laravelcompany.com for in-depth tutorials and real-world use cases.

Happy coding!

Catalog Import/Export Errors

Our network