You are here:  » strategy needed for moving data around in the csv


strategy needed for moving data around in the csv

Submitted by Johnny N on Fri, 2010-01-15 16:58 in

This may have a short or long answer, I am interested in if there is a short answer.

I want to be able to take a csv file and move columns and data around as well as editing some cell data on the fly.

I know all this could be done parsing each line, cell by cell in loops, but is there any shortcuts to doing this?

Submitted by support on Fri, 2010-01-15 19:10

Hello Johnny,

That should be straight forward - in fact it's always best to create CSV rows in controlled way; rather than creating a row automatically by implode()'ing the $record. For example...

<?php
  
function myRecordHandler($record)
  {
    global 
$csv;
    
// edit any values as required here, for example:
    
$record["TITLE"] = strtoupper($record["TITLE"]);
    
// output csv row
    
fwrite($csv,$record["TITLE"].",");
    
fwrite($csv,$record["DESCRIPTION"].",");
    
fwrite($csv,$record["CATEGORY"]."\n");
    
// remember last one ends with new line instead of separator character!
  
}
  
// open output csv file for writing
  
$csv fopen("output.csv","w");
  
// create header row if required
  
fwrite($csv,"TITLE".",");
  
fwrite($csv,"DESCRIPTION".",");
  
fwrite($csv,"CATEGORY"."\n");
  
// parse input file to create output
  
MagicParser_parse("input.csv","myRecordHandler","csv|44|1|0");
  
// close output file
  
fclose($csv);
?>

Hope this helps!
Cheers,
David.