note 44315 deleted from function.fgetcsv by aidan

From: Date: Mon, 23 Aug 2004 06:26:05 +0000
Subject: note 44315 deleted from function.fgetcsv by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-75144@lists.php.net to get a copy of this message
Note Submitter: miked at droplab dot com ---- Here's a class to parse a csv file into a 2D array of results. It's very flexible and is loosely based on jc at goet dot net's example. Any feedback would be appreciated. Usage can be by explained by help() method: $myVar = new CSV(); $myVar->help(); Here's the class code: <? class CSV { var $raw_data; var $new_data; var $mapping; var $results = array(); var $errors = array(); function CRLFclean() { $replace = array( "\n", "\r", "\r\n" ); $this->raw_data = str_replace($replace,"\n",$this->raw_data); } function validKEY($v) { return ereg_replace("[^a-zA-Z0-9_\s]","",$v); } function stripENCLOSED(&$v,$eb) { if($eb!="" AND strpos($v,$eb)!==false) { if($v[0]==$eb) $v = substr($v,1,strlen($v)); if($v[strlen($v)-1]==$eb) $v = substr($v,0,-1); $v = stripslashes($v); } else return; } function CSV($filename,$delim,$enclosed_by="",$eol="\n") { //open the file $this->raw_data = implode("",file($filename)); // make sure all CRLF's are consistent $this->CRLFclean(); // use custom $eol (if exists) if($eol!="\n" AND trim($eol)=="") $this->error("Couldn't split data via empty \$eol, please specify a valid end of line character."); else { $this->new_data = @explode($eol,$this->raw_data); if(count($this->new_data)==0) $this->error("Couldn't split data via given \$eol.<li>\$eol='".$eol."'"); } foreach($this->new_data AS $index1=>$line) { $temp = @explode($delim,$line); if(trim($line)=="") // skip empty lines continue; elseif(count($temp)==0) // line didn't split properly so record error $this->errors[] = "Couldn't split data line ".$c." via given \$delim."; else { $data_set = array(); foreach($temp AS $field_index=>$field_value) { // Remove enclose characters $this->stripENCLOSED($field_value,$enclosed_by); // create data key if($index1==0) $this->mapping[] = $this->validKEY($field_value); else $data_set[$this->mapping[$field_index]] = $field_value; } if(count($data_set)>0) $this->results[] = $data_set; } unset($data_set); } return $this->results; } function error($msg) { exit( "<hr size=1 noshade>". "<font color=red face=arial size=3>". "<h2>CSV Class Exception</h2>". $msg. "<p><b>Script Halted</b>". "</font>". "<hr size=1 noshade>" ); } function help() { print( "<hr size=1 noshade>". "<font face=arial size=3>". "<h2>CSV Class Usage</h2>". "\$myVar = new CSV(\"path_to_my_file\",\"field delimeter\",\"fields enclosed by\",\"EOL character (defaults to \\n)\");<p>". "Output is a 2d result array (\$myVar->results)". "</font>". "<hr size=1 noshade>" ); } } ?>

« previous php.notes (#75144) next »