note 105772 added to function.file

From: Date: Tue, 13 Sep 2011 19:33:51 +0000
Subject: note 105772 added to function.file
Groups: php.notes 
Request: Send a blank email to php-notes+get-183158@lists.php.net to get a copy of this message
read from CSV data (file) into an array with named keys ... with or without 1st row = header (keys) (see 4th parameter of function call as true / false) <?php // -------------------------------------------------------------- function csv_in_array($url,$delm=";",$encl="\"",$head=false) { $csvxrow = file($url); // ---- csv rows to array ---- $csvxrow[0] = chop($csvxrow[0]); $csvxrow[0] = str_replace($encl,'',$csvxrow[0]); $keydata = explode($delm,$csvxrow[0]); $keynumb = count($keydata); if ($head === true) { $anzdata = count($csvxrow); $z=0; for($x=1; $x<$anzdata; $x++) { $csvxrow[$x] = chop($csvxrow[$x]); $csvxrow[$x] = str_replace($encl,'',$csvxrow[$x]); $csv_data[$x] = explode($delm,$csvxrow[$x]); $i=0; foreach($keydata as $key) { $out[$z][$key] = $csv_data[$x][$i]; $i++; } $z++; } } else { $i=0; foreach($csvxrow as $item) { $item = chop($item); $item = str_replace($encl,'',$item); $csv_data = explode($delm,$item); for ($y=0; $y<$keynumb; $y++) { $out[$i][$y] = $csv_data[$y]; } $i++; } } return $out; } // -------------------------------------------------------------- ?> fuction call with 4 parameters: (1) = the file with CSV data (url / string) (2) = colum delimiter (e.g: ; or | or , ...) (3) = values enclosed by (e.g: ' or " or ^ or ...) (4) = with or without 1st row = head (true/false) <?php // ----- call ------ $csvdata = csv_in_array( $yourcsvfile, ";", "\"", true ); // ----------------- // ----- view ------ echo "<pre>\r\n"; print_r($csvdata); echo "</pre>\r\n"; // ----------------- ?> PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array ... and other file-handling methods ^ ---- Server IP: 69.147.83.197 Probable Submitter: 188.193.184.239 ---- Manual Page -- http://www.php.net/manual/en/function.file.php Edit -- https://master.php.net/note/edit/105772 Del: integrated -- https://master.php.net/note/delete/105772/integrated Del: useless -- https://master.php.net/note/delete/105772/useless Del: bad code -- https://master.php.net/note/delete/105772/bad+code Del: spam -- https://master.php.net/note/delete/105772/spam Del: non-english -- https://master.php.net/note/delete/105772/non-english Del: in docs -- https://master.php.net/note/delete/105772/in+docs Del: other reasons-- https://master.php.net/note/delete/105772 Reject -- https://master.php.net/note/reject/105772 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183158) next »