<?php
function csvLine($fields = array(), $delimiter = ',', $enclosure = '"')
{
if ($delimiter!=NULL)
	{
	if( strlen($delimiter) < 1 )
		{
		trigger_error('delimiter must be a character', E_USER_WARNING);
		return false;
		}
	elseif( strlen($delimiter) > 1 )
		{
		trigger_error('delimiter must be a single character', E_USER_NOTICE);
		}

	// use first character from string
	$delimiter = $delimiter[0];
	}
if( $enclosure!=NULL )
	{
	if( strlen($enclosure) < 1 )
		{
		trigger_error('enclosure must be a character', E_USER_WARNING);
		return false;
		}
	elseif( strlen($enclosure) > 1 )
		{
		trigger_error('enclosure must be a single character', E_USER_NOTICE);
		}
		// use first character from string
		$enclosure = $enclosure[0];
	}

	$i = 0;
	$csvline      = '';
	$escape_char  = '\\';
	$field_cnt    = count($fields);
	$enc_is_quote = in_array($enclosure, array('"',"'"));
	reset($fields);

	foreach( $fields AS $field )
		{
		// enclose a field that contains a delimiter, an enclosure character, or a newline
		if( is_string($field) && (
			strpos($field, $delimiter)!==false ||
			strpos($field, $enclosure)!==false ||
			strpos($field, $escape_char)!==false ||
			strpos($field, "\n")!==false ||
			strpos($field, "\r")!==false ||
			strpos($field, "\t")!==false ||
			strpos($field, ' ')!==false ) )
				{
				$field_len = strlen($field);
				$escaped = 0;
				$csvline .= $enclosure;
		for( $ch = 0; $ch < $field_len; $ch++ )
		    {
		    if( $field[$ch] == $escape_char && $field[$ch+1] == $enclosure && $enc_is_quote )
			{
			continue;
			}
		    elseif( $field[$ch] == $escape_char )
			{
			$escaped = 1;
			}
		    elseif( !$escaped && $field[$ch] == $enclosure )
			{
			$csvline .= $enclosure;
			}
		    else
			{
			$escaped = 0;
			}
		    $csvline .= $field[$ch];
		    }
		$csvline .= $enclosure;
		}
	else
		{
		$csvline .= $field;
		}

	if( $i++ != $field_cnt )
		{
		$csvline .= $delimiter;
		}
	}
	$csvline .= "\n";
	return $csvline;
}
?>