. * * @category PHP * @author V.Krishn * @copyright Copyright (c) 2012-2024 V.Krishn * @license GPL * @link http://github.com/insteps/phputils * @version 0.1.3 * */ /** * Parse a CSV string into an array for php 4+. * @param string $input String * @param string $delimiter String * @param string $enclosure String * @return array */ function str_getcsv4($input, $delimiter = ',', $enclosure = '"') { if ( ! preg_match("/[$enclosure]/", $input) ) { return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input)); } $token = "##"; $token2 = "::"; //alternate tokens "\034\034", "\035\035", "%%"; $t1 = preg_replace(array("/\\\[$enclosure]/", "/$enclosure{2}/", "/[$enclosure]\\s*[$delimiter]\\s*[$enclosure]\\s*/", "/\\s*[$enclosure]\\s*/"), array($token2, $token2, $token, $token), trim(trim(trim($input), $enclosure))); $a = explode($token, $t1); foreach($a as $k=>$v) { if ( preg_match("/^{$delimiter}/", $v) || preg_match("/{$delimiter}$/", $v) ) { $a[$k] = trim($v, $delimiter); $a[$k] = preg_replace("/$delimiter/", "$token", $a[$k]); } } $a = explode($token, implode($token, $a)); return (array)preg_replace(array("/^\\s/", "/\\s$/", "/$token2/"), array('', '', $enclosure), $a); } /** * Parse a CSV string into an array for php 4+. (Alternate) * @param string $input String * @param string $delimiter String * @param string $enclosure String * @return array */ function str_getcsv4a($input, $delimiter = ',', $enclosure = '"') { if ( ! preg_match("/[$enclosure]/", $input) ) { return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input)); } $a = explode($delimiter, $input); $on = NULL; foreach($a as $k=>$v) { if ( preg_match("/{$enclosure}$/", rtrim($v)) ) { $on = 0; $c[] = $v; $b[] = trim(trim(implode(',', $c)), $enclosure); unset($c); continue; } if ( preg_match("/^{$enclosure}/", ltrim($v)) ) { $on = 1; unset($c); $v = ltrim(ltrim($v), $enclosure); } if ( $on ) { $c[] = $v; continue; } $b[] = trim($a[$k]); } return (array)$b; } /** * Process an Array to CSV string. * @param string $fields Array * @param string $mode String * @param string $size Integer * @return string */ function csvstr(array $fields, $mode='+', int $size=1) : string { //$fp = fopen('php://memory', 'r'.$dbtable_mode); # ALT $sizeMBs = $size * 1024 * 1024; // output upto 1MB is kept in memory, // if it becomes bigger it will be written to a temporary file $fp = fopen("php://temp/maxmemory:$sizeMBs", 'r'.$mode); if ( fputcsv($fp, $fields) === false ) { return false; } rewind($fp); $csv_line = stream_get_contents($fp); // string fclose($fp); return rtrim($csv_line); } if ( ! function_exists('str_getcsv')) { function str_getcsv($input, $delimiter = ',', $enclosure = '"') { //return str_getcsv4($input, $delimiter, $enclosure); //OLDER return str_getcsv4a($input, $delimiter, $enclosure); //NEWER } }