CVS文件转换成php数组
sample.csv ---------------- name,email 政府,gov@gov.gov ---------------- ======================================= <?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('/^"(.+)"[\r\n]*$/', $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);