陳力維  ·  3年前
2 貼文  ·  0 留言

[PHP]匯入的csv包含逗號處理方式

遇到編輯提供的csv,某些欄位有逗號 "," ,編輯在該欄位有用雙引號標示

如:

test,aa,"aa ,dfg",123

網路上一時找不到解法,想了個解析方式如下

$dirPath = "/home/";
$filePath = $dirPath."test.csv";

if(!is_file($filePath)){
        exit;
}

$text = file_get_contents($filePath);
if(!isset($text) || strlen($text) < 1){
        exit;
}
$arr = explode("\n", $text);

if(isset($arr) && count($arr) > 0){
        foreach($arr as $ak => $av){

                if(!isset($av) || preg_match("/switch/i", $av) || strlen($av) < 1){
                        continue;
                }
                //print_r($av); echo "\n"; exit;

                $tmp = explodeSpecial($av);
                $tmp2 = explode(",",$str);
                print_r("tmp:".$tmp."\n");print_r("temp2:".$tmp2); exit;
        }
}

function explodeSpecial($str){
  $tempArr=explode('"',$str);
  //有雙數的雙引號才特殊處理
  if(count($tempArr)>1 && count($tempArr)%2!=0){
    $dic=[];
    //有特殊字元存取  1,3,5,7,9
    for($i=0;$i<count($tempArr);$i++){
      if($i%2==0){continue;}
      $dic["special_word_".$i]=$tempArr[$i];
      $tempArr[$i]="special_word_".$i;
    }
    $temp=join("",$tempArr);
    $replaceArr = explode(",",$temp);
    for($i==0;$i<count($replaceArr);$i++){
      if(isset($dic[$replaceArr[$i]])){
        $replaceArr[$i]=$dic[$replaceArr[$i]];
      }
    }
    return $replaceArr;
  }else{
    return explode(",",$str);
  }
}
/*
output:
tmp:Array
(
    [0] => test
    [1] => aa
    [2] => aa ,dfg
    [3] => 123
)
tmp2:Array
(
    [0] => test
    [1] => aa
    [2] => "aa 
    [3] => dfg"
    [4] => 123
)
*/
  分享   共 1,898 次點閱
按了喜歡:
共有 1 則留言
尤川豪   ·  3年前
445 貼文  ·  275 留言

我也遇過這問題,因為 csv 正式規格好像就是這樣,所以我後來是找了專門的套件來讀取

https://github.com/thephpleague/csv

呵呵~

 
按了喜歡:
您的留言
陳力維
2 貼文  ·  0 留言
查看所有文章