Using PHP Combine Multiple CSV Files into One CSV File

Use below PHP Script to merge CSV files into one master CSV file and optional to remove CSV header line.

<?php

/**
 * 7design.studio
 * Merge multiple CSV files into one master CSV file 
 * Remove header line from individual file
 */

$directory = "FOLDERDIRECTORY/*"; // CSV Files Directory Path

// Open and Write Master CSV File
$masterCSVFile = fopen('master-record.csv', "w+");

// Process each CSV file inside root directory
foreach(glob($directory) as $file) {

    $data = []; // Empty Data

    // Allow only CSV files
    if (strpos($file, '.csv') !== false) {

        // Open and Read individual CSV file
        if (($handle = fopen($file, 'r')) !== false) {
            // Collect CSV each row records
            while (($dataValue = fgetcsv($handle, 1000)) !== false) {
                $data[] = $dataValue;
            }
        }

        fclose($handle); // Close individual CSV file 
        
        unset($data[0]); // Remove first row of CSV, commonly tends to CSV header

        // Check whether record present or not
        if(count($data) > 0) {

            foreach ($data as $value) {
                try {
                   // Insert record into master CSV file
                   fputcsv($masterCSVFile, $value, ", ", "'");
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            
            }

        } else {
            echo "[$file] file contains no record to process.";
        }

    } else {
        echo "[$file] is not a CSV file.";
    }

}

// Close master CSV file 
fclose($masterCSVFile);

?>

Download the Script

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2018 7Design.Studio | Web Design, Web Application Development & UX Design | Chennai | India

Up ↑