2013-03-16 16 views

回答

18

這是一個簡單的方法來做到這一點。我不知道是什麼人做的,但我用這個

這是我的CSV讀者庫

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 

class CSVReader { 

    var $fields;   /** columns names retrieved after parsing */ 
    var $separator = ';'; /** separator used to explode each line */ 
    var $enclosure = '"'; /** enclosure used to decorate each field */ 

    var $max_row_size = 4096; /** maximum row size to be used for decoding */ 

    function parse_file($p_Filepath) { 

     $file = fopen($p_Filepath, 'r'); 
     $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure); 
     $keys_values = explode(',',$this->fields[0]); 

     $content = array(); 
     $keys = $this->escape_string($keys_values); 

     $i = 1; 
     while(($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) {    
      if($row != null) { // skip empty lines 
       $values = explode(',',$row[0]); 
       if(count($keys) == count($values)){ 
        $arr = array(); 
        $new_values = array(); 
        $new_values = $this->escape_string($values); 
        for($j=0;$j<count($keys);$j++){ 
         if($keys[$j] != ""){ 
          $arr[$keys[$j]] = $new_values[$j]; 
         } 
        } 

        $content[$i]= $arr; 
        $i++; 
       } 
      } 
     } 
     fclose($file); 
     return $content; 
    } 

    function escape_string($data){ 
     $result = array(); 
     foreach($data as $row){ 
      $result[] = str_replace('"', '',$row); 
     } 
     return $result; 
    } 
} 
?> 

和控制器的方法

function readExcel() 
{ 
     $this->load->library('csvreader'); 
     $result = $this->csvreader->parse_file('Test.csv'); 

     $data['csvData'] = $result; 
     $this->load->view('view_csv', $data); 
} 

這是鑑於

<table cellpadding="0" cellspacing="0" width="100%"> 
    <tr> 
      <td width = "10%">ID</td> 
      <td width = "20%">NAME</td> 
      <td width = "20%">SHORT DESCRIPTION</td> 
      <td width = "30%">LONG DESCRIPTION</td> 
      <td width = "10%">STATUS</td> 
      <td width = "10%">PARENTID</td> 
    </tr> 

      <?php foreach($csvData as $field){?> 
       <tr> 
        <td><?php echo $field['id']?></td> 
        <td><?php echo $field['name']?></td> 
        <td><?php echo $field['shortdesc']?></td> 
        <td><?php echo $field['longdesc']?></td> 
        <td><?php echo $field['status']?></td> 
        <td><?php echo $field['parentid']?></td> 
       </tr> 
      <?php }?> 
</table> 

參考Here

+0

Thx Raheel,你是否實現了這個輸入csv到數據庫呢? – 2013-03-16 17:12:52

+0

是的只是將'$ result'傳遞給數據庫表或根據您的要求形成一個數組。 – 2013-03-16 17:47:43

3

這是raheel山的接受的答案的改進版本 - 我編輯他的答案,但我的編輯被拒絕,但它是一個重要的轉變......

當分析每個數據行,它不是明智的做法是使用explode()上因爲這不包含逗號包含引號的字符串。爆炸斷裂這些字符串成子和$values提供額外的數組元素,所以這個檢查失敗:

if (count($keys) == count($values)) { 

取而代之的是,PHP有一個專用的方法來處理這個問題; str_getcsv()。我相應地更新了原始答案。

CSV閱讀庫:

<?php 
if (!defined('BASEPATH')) 
    exit('No direct script access allowed'); 

class CSVReader { 

    var $fields;/** columns names retrieved after parsing */ 
    var $separator = ';';/** separator used to explode each line */ 
    var $enclosure = '"';/** enclosure used to decorate each field */ 
    var $max_row_size = 4096;/** maximum row size to be used for decoding */ 

    function parse_file($p_Filepath) { 

     $file = fopen($p_Filepath, 'r'); 
     $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure); 
     $keys = str_getcsv($this->fields[0]); 

     $i = 1; 
     while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) { 
      if ($row != null) { // skip empty lines 
       $values = str_getcsv($row[0]); 
       if (count($keys) == count($values)) { 
        $arr = array(); 
        for ($j = 0; $j < count($keys); $j++) { 
         if ($keys[$j] != "") { 
          $arr[$keys[$j]] = $values[$j]; 
         } 
        } 

        $content[$i] = $arr; 
        $i++; 
       } 
      } 
     } 
     fclose($file); 
     return $content; 
    } 

} 
?> 

控制器的方法:

function readExcel() { 
    $this->load->library('csvreader'); 
    $result = $this->csvreader->parse_file('Test.csv'); 
    $data['csvData'] = $result; 
    $this->load->view('view_csv', $data); 
} 

而且本所認爲:

<table cellpadding="0" cellspacing="0" width="100%"> 
    <tr> 
     <td width="10%">ID</td> 
     <td width="20%">NAME</td> 
     <td width="20%">SHORT DESCRIPTION</td> 
     <td width="30%">LONG DESCRIPTION</td> 
     <td width="10%">STATUS</td> 
     <td width="10%">PARENTID</td> 
    </tr> 
    <?php foreach ($csvData as $field) { ?> 
     <tr> 
      <td><?php echo $field['id'] ?></td> 
      <td><?php echo $field['name'] ?></td> 
      <td><?php echo $field['shortdesc'] ?></td> 
      <td><?php echo $field['longdesc'] ?></td> 
      <td><?php echo $field['status'] ?></td> 
      <td><?php echo $field['parentid'] ?></td> 
     </tr> 
    <?php } ?> 
</table> 
2

那麼我不介意,我只是修改ajmedway的庫以包含分隔符,以防萬一您想從中獲取數據,讓我們說TSV或管道分隔文件。如果你想要簡單的舊CSV他就好了。

class CSVReader { 

var $fields;/** columns names retrieved after parsing */ 
var $separator = ';';/** separator used to explode each line */ 
var $enclosure = '"';/** enclosure used to decorate each field */ 
var $max_row_size = 4096;/** maximum row size to be used for decoding */ 

function parse_file($p_Filepath, $delimiter = FALSE) { 

    $file = fopen($p_Filepath, 'r'); 
    $this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure); 
    if ($delimiter==FALSE) 
    { 
    $keys = str_getcsv($this->fields[0]); 

    $i = 1; 
    while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) { 
     if ($row != null) { // skip empty lines 
      $values = str_getcsv($row[0]); 
      if (count($keys) == count($values)) { 
       $arr = array(); 
       for ($j = 0; $j < count($keys); $j++) { 
        if ($keys[$j] != "") { 
         $arr[$keys[$j]] = $values[$j]; 
        } 
       } 

       $content[$i] = $arr; 
       $i++; 
      } 
     } 
    } 
    } 
    else{ 
     $keys = str_getcsv($this->fields[0],$delimiter); 

     $i = 1; 
     while (($row = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure)) != false) { 
      if ($row != null) { // skip empty lines 
       $values = str_getcsv($row[0],$delimiter); 
       if (count($keys) == count($values)) { 
        $arr = array(); 
        for ($j = 0; $j < count($keys); $j++) { 
         if ($keys[$j] != "") { 
          $arr[$keys[$j]] = $values[$j]; 
         } 
        } 

        $content[$i] = $arr; 
        $i++; 
       } 
      } 
     } 
    } 

    fclose($file); 
    return $content; 
}}?> 
+0

如果($ delimiter = FALSE)這是錯誤的,因爲您將$ delimiter設置爲FALSE並且未檢查其狀態。它應該是if($ delimiter == FALSE) – Johnish 2016-09-30 19:42:37

+0

哎呦!抱歉。菜鳥的錯誤。謝謝@Johnish。我會立即糾正它。 – 2016-10-11 10:35:22

0

這是空行和多餘的空格和製表符的改進版本...

類CSVReader {

function csv_to_array($Filepath) 
{ 
    //Get csv file content 
    $csvData = file_get_contents($Filepath); 

    //Remove empty lines 
    $csvData = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\r\n", $csvData); 

    //String convert in array formate and remove double quote(") 
    $array = array(); 
    $array = $this->escape_string(preg_split('/\r\n|\r|\n/', $csvData)); 
    $new_content_in_array = array(); 
    if($array) 
    { 
     //Get array key 
     $array_keys = array(); 
     $array_keys = array_filter(array_map('trim', explode(';',$array[0]))); 

     //Get array value 
     $array_values = array(); 
     for ($i=1;$i<count($array);$i++) 
     { 
      if($array[$i]) 
      { 
       $array_values[] = array_filter(array_map('trim', explode(';',$array[$i]))); 
      } 
     } 

     //Convert in associative array 
     if($array_keys && $array_values) 
     { 
      $assoc_array = array(); 
      foreach ($array_values as $ky => $val) 
      {   
       for($j=0;$j<count($array_keys);$j++){ 
        if($array_keys[$j] != "" && $val[$j] != "" && (count($array_keys) == count($val))) 
        { 
         $assoc_array[$array_keys[$j]] = $val[$j]; 
        } 
       } 
       $new_content_in_array[] = $assoc_array; 
      } 
     } 
    } 
    return $new_content_in_array; 
} 

function escape_string($data){ 
    $result = array(); 
    foreach($data as $row){ 
     $result[] = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "", str_replace('"', '',$row)); 
    } 
    return $result; 
} 

} >

-1

呼叫控制器中:

$this->load->library('csvreader'); 
$import_csv_data = $this->csvreader->csv_to_array($path); 
print_r($import_csv_data); 
exit;