Filter/Edit CSV (Comma Separated Value) Data

CSV is very common format for data interchange. It is not as famous as XML and JSON but it is always easy to work with. CSV file can be opened directly in MS Excel and readable in any text editor. It does not take as much space as XML takes. It is easy to parse also compared to XML.

PHP has two beautiful functions to work with Comma Separated Value. One is fgetcsv() and another is fputcsv(). Today I used fputcsv() for the first time.

Here is a code I have used for filtering the third column which can have empty value. If that column has empty value then I will delete that entire row (actually I have ignored that row and have not considered in new file) and save the edited data.

<?php
$fp = fopen('CSV-File.csv', 'w');
$row = 1;
if (($handle = fopen("CSV-File.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        if (empty($data[2]))
        {
            echo "Empty $row<br>";
        }
        else
        {
            fputcsv($fp, $data);
        }
        $row++;
    }
    fclose($handle);
}
?>

Just now I have seen that I am using the same CSV file for reading and writing. Cannot it can cause infinite loop or some other error! In my case it has worked and it was for one time. So it is over for me. So, please you think.

  • # 2 - by JavaGenious

    Thanks for the Information. It really helped me to work on my project

  • # 3 - by William Taylor

    Thanks for sharing…this saved me so much time on a recent project.

Comments are open for an year period. Please, write here on Facebook page.