PHP file processing, extracting columns from a csv file

The php script below does a very simple job, which is extracting a specified column out of a csv file and put it into another csv file. It takes 4 command line arguments, the file name of the script itself, input file name, output file name, and the column number you want to extract. The index of the first column starts with 0. This script can be easily modified to extract more columns or do some tweaks to the data to be extracted.

<?php
$infile;
$outfile;
$column;
if( count($argv) < 4 )
{
	//php argv[0] argv[1] argv[2] argv[3]
	//The index of the first column is 0
	die("Usage: php csvParser.php inputfile.csv outputfile.txt columnNumber\n");
}
else
{
	$infile=$argv[1];
	$outfile=$argv[2];
	$column=$argv[3];
}

function getCsvColumn($infile, $outfile, $column)
{
	$fr = fopen($infile, 'r');
	$fw = fopen($outfile, 'w');
	if($fr!==false && $fw!==false)
	{
		while(($line=fgetcsv($fr,500,','))!==false)
		{
			fwrite($fw,$line[$column]."\n");//this line can be modified to extract more columns or tweak the data
		}
		fclose($fr);
		fclose($fw);
	}
}

//run the function to extract the specified column
getCsvColumn($infile, $outfile, $column);

Search within Codexpedia

Custom Search

Search the entire web

Custom Search