note 105209 modified in function.str-getcsv by danbrown

From: Date: Wed, 03 Aug 2011 13:22:39 +0000
Subject: note 105209 modified in function.str-getcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-182171@lists.php.net to get a copy of this message
For people who haven't got access to str_getcsv() in their version of PHP and want to convert strings from CSV, I have seen many huge swaths of code and regexes to do this extremely simple task. Here's minimal, fast code: <?php function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){ $fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1)); foreach ($fields as $key=>$value) $fields[$key]=str_replace($escape.$enclosure,$enclosure,$value); return($fields); } function array2csv($input,$delimiter=',',$enclosure='"',$escape='\\'){ foreach ($input as $key=>$value) $input[$key]=str_replace($enclosure,$escape.$enclosure,$value); return $enclosure.implode($enclosure.$delimiter.$enclosure,$input).$enclosure; } $data=array("one","\"two\""); for ($i=0;$i<100;$i++) $data=array(array2csv($data),$i); echo "Encoded $i times...".var_export($data,true)."\n"; for ($j=0;$j<$i;$j++) $data=csv2array($data[0]); echo "Decoded $i times...".var_export($data,true)."\n"; ?> Pretty straightforward. ;-) Yes, I intentionally changed the function names, --was-- For people who haven't got access to str_getcsv() in their version of PHP and want to convert strings from CSV, I have seen many huge swaths of code and regexes to do this extremely simple task. Here's minimal, fast code: function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){ $fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1)); foreach ($fields as $key=>$value) $fields[$key]=str_replace($escape.$enclosure,$enclosure,$value); return($fields); } function array2csv($input,$delimiter=',',$enclosure='"',$escape='\\'){ foreach ($input as $key=>$value) $input[$key]=str_replace($enclosure,$escape.$enclosure,$value); return $enclosure.implode($enclosure.$delimiter.$enclosure,$input).$enclosure; } $data=array("one","\"two\""); for ($i=0;$i<100;$i++) $data=array(array2csv($data),$i); echo "Encoded $i times...".var_export($data,true)."\n"; for ($j=0;$j<$i;$j++) $data=csv2array($data[0]); echo "Decoded $i times...".var_export($data,true)."\n"; Pretty straightforward. ;-) Yes, I intentionally changed the function names, http://php.net/manual/en/function.str-getcsv.php

« previous php.notes (#182171) next »