2

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);
}


?>
Patrick62
  • 71
  • 7

2 Answers2

2

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);
}
angel.bonev
  • 1,477
  • 1
  • 13
  • 21
1

If I understand your question correctly, you want to remove the first three lines, but only execute array_shift once. The simplest solution would be to use the array_shift function three times.

//delete fist 3 lines
array_shift($csv_data);
array_shift($csv_data);
array_shift($csv_data);

As for the deletion of the date: If its the last entry (or line) in your csv-file, you could use array_pop($csv_data), which removes the last entry from an array. If its not the last line, you could filter it inside your while loop, while filling the $csv_data array:

if(substr($data[0], 0, 4) === "data") {
    continue;
}

$csv_data[] = $data;

This would skip every line where the first cell string begins with "data", so it doesnt even get into the $csv_data array

Tyrmos
  • 367
  • 1
  • 11