Filter/Edit CSV (Comma Separated Value) Data

Jul 16th, 2010

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.

 
Possibly Related posts:
  1. July 19th, 2010 at 12:01 | #1

    i like your blog and thanks for sharing useful information.

  1. July 16th, 2010 at 21:18 | #1
Comments are closed. You are welcome to write on Facebook page.
blog comments powered by Disqus