RoRo
RoRo

Reputation: 15

Unset rows (based on row name) csv through php

I have a .CSV file with static column names. I receive it daily so i have to automatically edit it on a daily base.

On the first line are the row names for example: row1;row2;row3,row4,row5

for example when i want to unset "row2" and "row4".

How can i unset multiple rows based on a name?

I found a some tutorials about deleting lines or rows based on a row position but nothing that helps me completely.

This is what is have now:

$inFile  = 'original.csv';
$outFile = 'edited.csv';

$delimiter = ';';
$enclosure = '"';   

$read = fopen($inFile, 'r');
$write = fopen($outFile, 'w');
if ($write && $read) {
    while (($data = fgetcsv($read)) !== FALSE) {

        // how to unset multiple row names

        fputcsv($write, $data, $delimiter, $enclosure);
    }
}
fclose($write);
fclose($read);

Also, do i need to use the delimiter and enclosure when i fopen the original file?

Upvotes: 0

Views: 476

Answers (1)

khoekman
khoekman

Reputation: 1153

Hi you can try the updated following code:

$inFile  = 'original.csv';
$outFile = 'edited.csv';
$delimiter = ';';
$enclosure = '"';   
$removeFields = array('color');

$write = fopen($outFile, 'w');

if ($write) {
    $rows = file($inFile);
    $first = false;
    foreach($rows as $row) {
        $csvToPHP = str_getcsv($row, $delimiter, $enclosure);
        if (!$first) {
            $headers = array_flip($csvToPHP);
            $first = true;
        }

        foreach($removeFields as $remove) {
            unset($csvToPHP[$headers[$remove]]);
        }
        fputcsv($write, $csvToPHP, $delimiter, $enclosure);
    }   
}
fclose($write);

I used a test csv original.csv:

name,age,color
test1,20,red
test2,32,blue
test3,92,green
test4,12,red
test5,56,orange

Result edited.csv:

name
test1
test2
test3
test4
test5

Hope it helps. Good luck!

Upvotes: 1

Related Questions