How can the header line of the original CSV file be included in the split files during the splitting process?

To include the header line of the original CSV file in the split files during the splitting process, you can read the header line first and then append it to each split file as it is created. This ensures that each split file will have the header line included at the beginning.

<?php

// Open the original CSV file
$originalFile = fopen('original.csv', 'r');

// Read the header line
$header = fgetcsv($originalFile);

// Split the original CSV file into multiple files
$splitSize = 1000; // Number of rows per split file
$splitCount = 1;
$splitFile = fopen('split_' . $splitCount . '.csv', 'w');

// Write the header line to the first split file
fputcsv($splitFile, $header);

while (($data = fgetcsv($originalFile)) !== false) {
    fputcsv($splitFile, $data);

    if (ftell($originalFile) % $splitSize == 0) {
        fclose($splitFile);
        $splitCount++;
        $splitFile = fopen('split_' . $splitCount . '.csv', 'w');
        fputcsv($splitFile, $header); // Write the header line to the new split file
    }
}

fclose($originalFile);
fclose($splitFile);

?>