phpcsvfputcsv

How to remove specific lines from a csv file in php?


I have a csv file like this: enter image description here

I would like to delete the first 3 lines as well as the line 'Data as of' to have only my table of values.

I tried array_shift($csv_data); but it only removes the first line, how can I do it ?

<?php

//Modifications on csv file
$delimiter = ";"; 
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
        //Add columns with the name of pictures at the end of file : style_color.jpg 
        $data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" .$data[4].'.jpg' : '');   
        //Delete two columns with pictures
        unset($data[1]);
        unset($data[2]);
        $csv_data[] = $data;
        $row++;      
    }
    fclose($handle);
}
//delete fist 3 lines
array_shift($csv_data);

if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
    foreach ($csv_data as $data) {
        fputcsv($handle, $data, $delimiter);
    }
    fclose($handle);
}


?>

Solution

  • You can use array_slice and array_pop

    $csv_data = array_slice($csv_data, 3); // this will remove first three elements
    array_pop($csv_data);// this will remove last element from array
    

    But in you case you can skip adding them

    $delimiter = ";";
    $csv_data = array();
    $row = 1;
    if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
        while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
            //Add columns with the name of pictures at the end of file : style_color.jpg 
            $data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
            //Delete two columns with pictures
            unset($data[1]);
            unset($data[2]);
            if ($row > 3)//start adding after third row
                if (strpos($data[0], "Data as of") !== 0)//Dont add any line that starts with 'Data as of'
                    $csv_data[] = $data;
            $row++;
        }
        fclose($handle);
    }