Monday, May 14, 2012

Import .CSV file in PHP

This code will help you to import the .CSV file data into Database. This code was build in PHP. It is generic class which can use into different purpose.

Db.php
$con = mysql_connect("hostname","username","password");
mysql_select_db("dbname",$con);

Import.php
include('db.php');
class ImportComponent
{
    
    function array_remove_empty($arr){
 $narr = array();
 while(list($key, $val) = each($arr)){
     if (is_array($val)){
  $val = array_remove_empty($val);
  // does the result array contain anything?
  if (count($val)!=0){
      // yes :-)
      $narr[$key] = $val;
  }
     }
     else {
  if (trim($val) != ""){
      $narr[$key] = $val;
  }
     }
 }
 unset($arr);
 return $narr;
    }

   
    function import($file,$uid,$table){
 $row = 1;
 $status = "";
 if (($handle = fopen($file, "r")) !== FALSE) {
 while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
     if($row == 1){
  foreach ($data as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  
  if(strpos($result,'"') == true){
      $splitdata = split('"',$result);
      $splitdata = str_ireplace("'",'',$splitdata);
  }
  else{
      $splitdata = split("'",$splitdata);
  $splitdata = str_ireplace('"','',$splitdata);
  $dataval = $this->array_remove_empty($splitdata);
  $result = "";
  foreach ($dataval as &$datavalue) {
  $result=$result.$datavalue.",";
  }
  $result = substr($result, 0, -1);
  }
  $num = count($data);
  $row++;
  $valueresult = "";
  $datavalue = "";
  for ($c=0; $c < $num; $c++) {
     if($row > 2){
      $datavalue = $data[$c];
      $valueresult=$valueresult."'".$datavalue;
      $datavalueofsecrec = split('"',$valueresult);
      $datavalueofsecrec = str_ireplace("'",'',$datavalueofsecrec);
      $datavalueofsecrec = $this->array_remove_empty($datavalueofsecrec);
      $valueresult = "";
      foreach ($datavalueofsecrec as $finalval) {
   $valueresult=$valueresult."'".$finalval."',";
      }
      }
  }
  if($row > 2){     
      $query = "insert into $table($result) values($valueresult)";
      $status =  mysql_query($query);
  }
     }
 fclose($handle);
 }
 if($status)
 {
     return "Success";
 }
 else
 {
     echo "failed";
 }
    }
}

Form.php
include('import.php')
$obj = new Import();
 if($_FILES){
    $uploaddir = 'Directory path';
    $filename = $_FILES['file']['name'];
    $filesize = $_FILES['file']['size'];
    $tmpname_file = $_FILES['file']['tmp_name'];
    if($filesize > '1000000') {
    echo "Way too big!!";
    } else {
    move_uploaded_file($tmpname_file, "$uploaddir$filename");
         $status = $obj->import("$uploaddir$filename",$userid(Optional),$tablename);        
    }
 }

1 comment: