Return to Snippet

Revision: 59258
at August 28, 2012 13:46 by hgc81538


Initial Code
sample.csv
----------------
name,email
政府,[email protected]
한국,[email protected]
----------------

=======================================
<?php

function str_to_csv( $row )
{
	if( $row=='' )
	{
		return array();
	}
	$a = array();
	$src = explode(',', $row );
	do{
		$p = array_shift($src);
		while( mb_substr_count($p,'"') % 2 != 0 )
		{
			if( count($src)==0 ){ return false;	}
			$p .= ','.array_shift($src);
		}
		$match = null;
		if( preg_match('/^"(.+)"[
]*$/', $p, $match ))
		{
			$p = $match[1];
		}
		$a[] = str_replace('""','"',$p);
	}while( count($src) > 0 );
	return $a;
}


function file_getcsv( $f )
{
	$line = fgets( $f );
	while( ($a = str_to_csv($line))===false )
	{
		if( feof($f) ){	return false; }
		$line .= "\n".fgets( $f );
	}
	return $a;
}


function file_to_csv( $filename )
{
	ini_set("auto_detect_line_endings", true);
	$a = array();
	$f = fopen($filename,'r');
	while( !feof($f) )
	{
		$rec = file_getcsv($f);
		if( $rec===false ){	return false; }
		if( !empty($rec) )
		{
			$a[] = $rec;
		}
	}
	fclose($f);
	return $a;
}

$data = file_to_csv('sample.csv');

echo '<pre>';print_r($data);

Initial URL


Initial Description
CSV(unicode) file to php array

Initial Title
CSV(unicode) file to php array

Initial Tags
csv

Initial Language
PHP