[英]How to import csv file to mysql in codeigniter
我有一個csv文件格式,如您所見,這里有一個“ 2013年1月7日”,我該如何將其轉換為2013年1月7日。
WS-C3750X-48P-L,SOLAIRE,,FDO1651X2H9,"JAN. 7, 2013","JAN. 6, 2014",,1 Year,CISCO,Covered Under Warranty,30 Days,NA,"JAN. 2, 2013","APR. 2, 2014",1 Year and 3 Months,888-1,12643158
在csv文件中以這種格式出現的adadtional在我使用print_r()時顯示,但在最上面的示例中沒有插入。您能告訴我為什么嗎?
GLC-SX-MM,SOLAIRE,,AGM1620L2LU,No Records,No Records,,NA,NA,NA,NA,NA,No Records,No Records,NA,No Records,No Records
這是我使用的庫代碼。
碼:
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) {
$key_field = 'model,client_name,end_user,serial_num,trends_warranty_start,trends_warranty_end,client_contract_no,trends_warranty_period,vendor,support_coverage,sla,service_contract_num,support_coverage_start,support_coverage_end,support_coverage_period,trends_po,supplier_so';
$file = fopen($p_Filepath, 'r');
$this->fields = fgetcsv($file, $this->max_row_size, $this->separator, $this->enclosure);
$keys_values = explode(',',$key_field);
$content = array();
$keys = $this->escape_string($keys_values);
$i = 0;
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;
}
}
要將“ 2013年1月7日”轉換為2013年1月7日。
$str = 'JAN. 7, 2013';
echo date("Y-m-d", strtotime($str))
嘗試使用條件運算符來檢查需要轉換的字段。
如果我是你,我只會這樣做
for($j=0;$j<count($keys);$j++){
if($keys[$j] != ""){
if ($j == 4 || $j == 5 || $j == 12 || $j == 13) {
$new_values[$j] = date("Y-m-d", strtotime($new_values[$j]));
$arr[$keys[$j]] = $new_values[$j];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.