- // Ini_set ('memory _ limit ','-1'); // if the csv value is large, you can add it.
- /*
- * $ File: csv file
- * $ CsvDataArr: header of csv table, eg: arary ('name', 'sex', 'age') or array (0, 1, 2)
- * $ Specialhtml: whether do you want to convert special characters to html entities?
- * $ Removechar: which type do you want to remove special characters in array keys, manual or automatical?
- * Edit http://bbs.it-home.org
- */
- Class csv_to_array
- {
- Private $ counter;
- Private $ handler;
- Private $ length;
- Private $ file;
- Private $ seprator;
- Private $ specialhtml;
- Private $ removechar = 'manual ';
- Private $ csvDataArr;
- Private $ csvData = array ();
-
- Function _ construct ($ file = '', $ csvDataArr ='', $ specialhtml = true, $ length = 1000, $ seprator = ',')
- {
- $ This-> counter = 0;
- $ This-> length = $ length;
- $ This-> file = $ file;
- $ This-> seprator = $ seprator;
- $ This-> specialhtml = $ specialhtml;
- $ This-> csvDataArr = is_array ($ csvDataArr )? $ CsvDataArr: array ();
- $ This-> handler = fopen ($ this-> file, "r ");
- }
-
- Function get_array ()
- {
- $ GetCsvArr = array ();
- $ CsvDataArr = array ();
- While ($ data = fgetcsv ($ this-> handler, $ this-> length, $ this-> seprator ))! = FALSE)
- {
- $ Num = count ($ data );
- $ GetCsvArr [$ this-> counter] = $ data;
- $ This-> counter ++;
- }
- If (count ($ getCsvArr)> 0)
- {
- $ CsvDataArr = array_shift ($ getCsvArr );
- If ($ this-> csvDataArr) $ csvDataArr = $ this-> csvDataArr;
-
- $ Counter = 0;
- Foreach ($ getCsvArr as $ csvValue)
- {
- $ TotalRec = count ($ csvValue );
- For ($ I = 0; $ I <$ totalRec; $ I ++)
- {
- $ Key = $ this-> csvDataArr? $ CsvDataArr [$ I]: $ this-> remove_char ($ csvDataArr [$ I]);
- If ($ csvValue [$ I]) $ this-> csvData [$ counter] [$ key] = $ this-> put_special_char ($ csvValue [$ I]);
- }
- $ Counter ++;
- }
- }
- Return $ this-> csvData;
- }
-
- Function put_special_char ($ value)
- {
- Return $ this-> specialhtml? Str_replace (array ('&', '"', '\'',' <','> '), array ('&','"',''', '<', '>'), $ value): $ value;
- }
-
- Function remove_char ($ value)
- {
- $ Result = $ this-> removechar = 'manual '? $ This-> remove_char_manual ($ value): $ this-> remove_char_auto ($ value );
- Return str_replace ('', '_', trim ($ result ));
- }
-
- Private function remove_char_manual ($ value)
- {
- Return str_replace (array ('&', '"', '\'',' <','> ',' (',') ',' % '), '', trim ($ value ));
- }
-
- Private function remove_char_auto ($ str, $ x = 0)
- {
- $ X = 0? $ Str = $ this-> make_semiangle ($ str ):'';
- Eregi ('[: punct:]', $ str, $ arr );
- $ Str = str_replace ($ arr [0], '', $ str );
-
- Return eregi ('[: punct:]', $ str )? $ This-> remove_char_auto ($ str, 1): $ str;
- }
-
- Private function make_semiangle ($ str)
- {
- $ Arr = array ('0' => '0', '1' => '1', '2' => '2 ', '3' => '3', '4' => '4 ',
- '5' => '5', '6' => '6', '7' => '7', '8' => '8 ', '9' => '9 ',
- 'A' => 'A', 'B' => 'B', 'c' => 'C', 'D' => 'D ', 'E' => 'e ',
- 'F' => 'F', 'G' => 'G', 'H' => 'h', 'I' => 'I ', 'j' => 'J ',
- 'K' => 'K', 'L' => 'L', 'M' => 'm', 'n' => 'N ', 'o' => 'O ',
- 'P' => 'P', 'q' => 'Q', 'R' => 'R', 's' =>'s ', 'T' => 'T ',
- 'U' => 'u', 'V' => 'V', 'W' => 'W', 'x' => 'X ', 'y' => 'y ',
- 'Z' => 'Z', 'a' => 'A', 'B' => 'B', 'c' => 'C ', 'D' => 'D ',
- 'E' => 'e', 'F' => 'F', 'G' => 'G', 'H' => 'h ', 'I' => 'I ',
- 'J' => 'J', 'K' => 'K', 'L' => 'L', 'M' =>'m ', 'n' => 'N ',
- 'O' => 'O', 'P' => 'P', 'q' => 'Q', 'R' => 'R ','s '=>'s ',
- 'T' => 'T', 'u' => 'u', 'V' => 'V', 'W' => 'W ', 'X' => 'X ',
- 'Y' => 'y', 'Z' => 'Z ',
- '(' => '(', ')' => ')', '[' => '[', ']' => ']', '[' => '[',
- ']' => ']', '<' => '[', '<' => ']', '=> '[', '"' => ']',
- ''' => '[', ''' => ']', '{' => '{', '}' => '}', '=>' <',
- '"' => ',
- '%' => '%', '+' => '+', '-' => '-', '-' => '-','~ '=> '-',
- ':' => ':','. '=>'. ',', '=>', '=>'. ',', '=> '.',
- ';' => ',','? '=> '? ','! '=> '! ','... '=>'-', ''' =>' | ',
- '"' => '"', ''' => ''', ''' => ''', '|' => '| ', 'Region' => '"',
- ''=>'', '$' => '$', '@' => '@', '#' => '#', '^' => '^', '&' => '&', '*' => '*');
-
- Return strtr ($ str, $ arr );
- }
-
- Function _ destruct (){
- Fclose ($ this-> handler );
- }
- }
- // Example:
- $ Csv = new csv_to_array('user.csv ');
- Echo"
"; print_r($csv->get_array()); echo " ";
- ?>
2. use common functions
- Function csv_to_array ($ csv)
- {
- $ Len = strlen ($ csv );
-
-
- $ Table = array ();
- $ Cur_row = array ();
- $ Cur_val = "";
- $ State = "first item ";
-
-
- For ($ I = 0; $ I <$ len; $ I ++)
- {
- // Sleep (1, 1000 );
- $ Ch = substr ($ csv, $ I, 1 );
- If ($ state = "first item ")
- {
- If ($ ch = '"') $ state =" we're quoted hea ";
- Elseif ($ ch = ",") // empty
- {
- $ Cur_row [] = ""; // done with first one
- $ Cur_val = "";
- $ State = "first item ";
- }
- Elseif ($ ch = "\ n ")
- {
- $ Cur_row [] = $ cur_val;
- $ Table [] = $ cur_row;
- $ Cur_row = array ();
- $ Cur_val = "";
- $ State = "first item ";
- }
- Elseif ($ ch = "\ r") $ state = "wait for a line feed, if so close out row! ";
- Else
- {
- $ Cur_val. = $ ch;
- $ State = "gather not quote ";
- }
-
- }
-
- Elseif ($ state = "we're quoted hea ")
- {
- If ($ ch = '"') $ state =" potential end quote found ";
- Else $ cur_val. = $ ch;
- }
- Elseif ($ state = "potential end quote found ")
- {
- If ($ ch = '"')
- {
- $ Cur_val. = '"';
- $ State = "we're quoted hea ";
- }
- Elseif ($ ch = ',')
- {
- $ Cur_row [] = $ cur_val;
- $ Cur_val = "";
- $ State = "first item ";
- }
- Elseif ($ ch = "\ n ")
- {
- $ Cur_row [] = $ cur_val;
- $ Table [] = $ cur_row;
- $ Cur_row = array ();
- $ Cur_val = "";
- $ State = "first item ";
- }
- Elseif ($ ch = "\ r") $ state = "wait for a line feed, if so close out row! ";
- Else
- {
- $ Cur_val. = $ ch;
- $ State = "we're quoted hea ";
- }
-
- }
- Elseif ($ state = "wait for a line feed, if so close out row! ")
- {
- If ($ ch = "\ n ")
- {
- $ Cur_row [] = $ cur_val;
- $ Cur_val = "";
- $ Table [] = $ cur_row;
- $ Cur_row = array ();
- $ State = "first item ";
-
- }
- Else
- {
- $ Cur_row [] = $ cur_val;
- $ Table [] = $ cur_row;
- $ Cur_row = array ();
- $ Cur_val = $ ch;
- $ State = "gather not quote ";
- }
- }
-
- Elseif ($ state = "gather not quote ")
- {
- If ($ ch = ",")
- {
- $ Cur_row [] = $ cur_val;
- $ Cur_val = "";
- $ State = "first item ";
-
- }
- Elseif ($ ch = "\ n ")
- {
- $ Cur_row [] = $ cur_val;
- $ Table [] = $ cur_row;
- $ Cur_row = array ();
- $ Cur_val = "";
- $ State = "first item ";
- }
- Elseif ($ ch = "\ r") $ state = "wait for a line feed, if so close out row! ";
- Else $ cur_val. = $ ch;
- }
-
- }
-
- Return $ table;
- }
-
- // Pass a csv string, get a php array
- // Example:
- $ Arr = csv_to_array(file_get_contents('user.csv '));
- Echo"
"; print_r($arr); echo " "
- ?>
-
Or
- $ ArrCSV = array ();
- // Open the CSV
- If ($ handle = fopen ("user.csv", "r "))! = FALSE ){
- // Set the parent array key to 0
- $ Key = 0;
- // While there is data available loop through unlimited times (0) using separator (,)
- While ($ data = fgetcsv ($ handle, 0 ,","))! = FALSE ){
- // Count the total keys in each row
- $ C = count ($ data );
- // Populate the array
- For ($ x = 0; $ x <$ c; $ x ++) $ arrCSV [$ key] [$ x] = $ data [$ x];
- $ Key ++;
- } // End while
- // Close the CSV file
- Fclose ($ handle );
- } // End if
- Echo"
"; print_r($arrCSV); echo " ";
- ?>
As for which one is better, it depends on your actual needs and hobbies. in actual work, there are still a lot of requirements for converting csv to array. we suggest you practice more and learn more. |