Simple .csv file parser

In the following short snippet is an example of using PHP for simple parsing of .csv file / files comparing them and outputting the results in a third file. In this case itself it is not appropriate for use on live websites/apps since it is really inefficient, but I liked the simplicity and quick adaptability as a basis 🙂 The snippet uses only functions and libs from PHP itself (5.2+)


$all_acc_file = fopen('big_original_file.csv', 'r'); // test matchingdatacheck.csv
$result_file = fopen("result.csv","w");

$i = 0;
while (($line = fgetcsv($all_acc_file)) !== FALSE) {
   //$line is an array of the csv elements
   $file_missmatch = fopen('comparison_table.csv', 'r');
   while (($linemiss = fgetcsv($file_missmatch)) !== FALSE) {

   //matching in this example twelth or seventh entry beetwen a line in big_original_file.csv and a line in comparison_table.csv
   if($line[11] == $linemiss[11] || $line[6] == $linemiss[6]){
     $result_arr = array($linemiss[2] , $linemiss[3] , $line[2] , $line[3],$line[11],$line[6]);

   fputcsv($result_file, $result_arr);

 $i++; echo"$i\n";

By |September 13th, 2014|Categories: ALL|Tags: , , |

About the Author:

Senior lead developer currently working in Java, architecture design, mix of tech from Front-end in JS and templating to chef,rundeck etc. For fun and challenge I am writing different blog posts from stories to poems, programming tutorials and many more. Currently working on my Masters degree on a part-time basis.