Programatically edit a CSV file

Posted by & filed under PHP.

Here’s an example of adding a leading zero to columns 2 and 3 of the CSV file:

$input = fopen('numbers.csv','r');
$output = fopen('numbers_touched.csv','w');
while($csv_line = fgetcsv($input,1024)) {
	$line = array();
	foreach ($csv_line as $k => $field){
		if ($k == 2 || $k == 3) {
			$field = '0' . $field;
		}
		$line[] = $field;
	}
	fputcsv($output,$line);
}
fclose($input);
fclose($output);

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Bitnami