尝试读取混乱的CSV文件

时间:2019-03-29 11:37:46

标签: php csv

我正在尝试使用fgetcsv()php函数读取CSV file,但是它没有获取应有的详细信息。我发现CSV文件杂乱无章,并且在开始和中间存在多个不相关的逗号。如何使该CSV清洁程序?

我使用了str_replace()php函数来删除逗号的三元组,但是开始时的逗号仍然给我带来了问题。我也尝试过ltrim(),但是也没有用。

<?php
    $file = "grid.csv";
    $s = file_get_contents($file);
    $s = str_replace(",,,", "", $s);
    //$s = ltrim($s,",");
    $f = "grid1.csv";
    $handle = fopen($f, "w");
    fwrite($handle, $s);
?>

我希望此代码的输出是干净的csv文件。但是从现在开始,在新文件中也会出现多个逗号。

这是我尝试使用fgetcsv()读取文件的主要代码。

if(isset($_POST["submit"])){
    echo "in submit</br>";
    if($_FILES['csv_info']['name']){
        echo "some file</br>";
        $filename = explode(".", $_FILES['csv_info']['name']);
        if(end($filename) == 'csv'){
            echo "file is csv</br>".$_FILES['csv_info']['tmp_name'];
            $handle = fopen($_FILES['csv_info']['tmp_name'],"r");
            $sid = 0;
            //$query = "select exists(select 1 from tblMarks)";
            //$choice = mysqli_query($conn, $query);
            while($data = fgetcsv($handle)){
                if($sid == 0){
                    $sid = $sid + 1;
                    continue;
                }
                //echo $data;
                $name = mysqli_real_escape_string($conn, $data[0]);
                $physics = mysqli_real_escape_string($conn, $data[1]);
                $maths = mysqli_real_escape_string($conn, $data[2]);
                $chemistry = mysqli_real_escape_string($conn, $data[3]);
                $bio = mysqli_real_escape_string($conn, $data[4]);
                $sst = mysqli_real_escape_string($conn, $data[5]);
                echo "</br>inserting sid".$sid." name=".$name." physics=".$physics." maths=".$maths." chemistry=".$chemistry." bio=".$bio." sst=".$sst."</br>";
                //$query = "insert into tblMarks (sid, name, physics, maths, chemistry, bio, sst) values ('$sid', '$name', '$physics', '$maths','$chemistry','$bio','$sst') on duplicate key update name = '$name', physics = '$physics',maths = '$maths', chemistry = '$chemistry', bio = '$bio', sst ='$sst'";
                //mysqli_query($conn, $query);
                $sid = $sid + 1;
            }
            fclose($handle);
        }
        else{
            $message = '<label class="text-danger">Please Select CSV File Only</lable>';
        }
    }
    else{
        $message = '<label class="text-danger">Please Select File</label>';
    }
}

输出是这样的:

OUTPUT

1 个答案:

答案 0 :(得分:1)

这是逐行读取CSV文件的正确方法。 CSV文件中有很多行具有空白值,以删除已使用主题 array_filter

$temp = array();
if (($h = fopen("grid.csv", "r")) !== FALSE) 
{
  // Convert each line into the local $data variable
  while (($data = fgetcsv($h, 1000, ",")) !== FALSE) 
  {     
    $data = array_filter($data);
    if(count($data) > 0){
        $temp[] = $data;
    }
  }
  fclose($h);
}

//Write csv file

$fp = fopen('grid1.csv', 'w');
foreach ($temp as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);