Extracting Microsfoft Excel CSV in PHP

I deal with lots of data. Data that people want extracted from our product database into their custom format and also they want us to manipulate their data. What I've done here is take the MS Excel CSV file which only wraps text in quotes if it has a comma in it. Hope it helps to import MS Excel CSV into a standard PHP array.

<?php

$file = './test.csv';
updateFile( $file );

function updateFile( $fileName )
{
	$F = fopen( $fileName, 'r' );
	//	get header of file
	$header = fgets( $F, 1024 );
	$header = trimLine( $header );
	$header = csvExtract( $header );
	
	while( $r = fgets( $F, 1024 ) )
	{
		$r = trimLine( $r );
		$rows[] = csvExtract( $r, $header, false );
		
	}
}

function trimLine( $str )
{
	return trim( str_replace( "\r", '', str_replace( "\n", '', $str ) ) );
}

function csvExtract( $str, $header = array(), $stop = false )
{
	$a = array();
	$row = split( ",", $str );
	$flag = false;
	foreach( $row as $k => $v )
	{
		//	If not flagged and starts with quote and doesn't end with quote
		if( $flag == false && substr( $v, 0, 1 ) == '"' && substr( $v, strlen($v)-1, 1 ) != '"' )
		{
			$flag = true;
			$a[] = $v;
		//	if flag is true then combine with last round
		} elseif( $flag == true )
		{
			$a[count($a)-1] .= ','.$v;
			//	If line ends with quote but not double quote then set flag back to false
			if( substr( $v, strlen($v)-1, 1 ) == '"' && substr( $v, strlen($v)-2, 2 ) != '""' )
				$flag = false;
		//	if flag isn't set and doesn't trigger flag setting then just add to array
		} else {
			$a[] = $v;
		}
	}
	
	//	If the $stop flag is set then output the first true row with headers
	if( $stop == true )
	{
		foreach( $a as $k => $v )
		{
			print $header[$k].": $v\n";
		}
		exit;
	}
	return $a;
}
Powered by Drupal, an open source content management system