fgetcsv not reading csv file properly that is save

2019-09-06 01:55发布

I'm trying to import some data through csv file into my database. The problem is that in the very beginning of the development I was using windows so my csv file was written on ms office. So while importing there it works fine. But switching to linux(UBUNTU) while saving the csv file it's not showing data as i want. I'm not getting any solution either.

This is the array which is generated by the csv that has been made by ms office on windows machine which works fine.

Array
(
[0] => Array
    (
        [0] => Student Name
        [1] => Student Roll
        [2] => Class
        [3] => Section
        [4] => Exam
        [5] => Subject
        [6] => Total Marks
        [7] => Grade
        [8] => Objective
        [9] => Subjective
        [10] => Practical
    )

[1] => Array
    (
        [0] => Sample Name
        [1] => 123
        [2] => Nine
        [3] => A
        [4] => Mid Term
        [5] => Math
        [6] => 80
        [7] => A+
        [8] => 40
        [9] => 20
        [10] => 20
    )

)

But in linux my csv format is not working correctly. It's pushing all the data into one key & one element like below.

Array
(
[0] => Array
    (
        [0] => Student Name Student Roll    Class   Section Exam    Subject Total Marks Grade   Objective   Subjective  Practical
    )

[1] => Array
    (
        [0] => Samp0le Name 123 Nine    A   Mid Term    Math    80  A+  40  20  20
    )

)

So my actual question is how can I get read of that?

This is my coding for the upper array generation:

$csv = array();
    //$file = fopen('myCSVFile.csv', 'r');
    ini_set("auto_detect_line_endings", true);
    while (($result = fgetcsv($fp)) !== false)
    {
        $csv[] = $result;
    }

    fclose($fp);

    echo '<pre>';
    print_r($csv);
    echo '</pre>';

Please help me I'm in very need actually ..

2条回答
女痞
2楼-- · 2019-09-06 02:02

You have saved the file as - separate values using tab and not by commas. Again save as the same file and select commas as delimiter for values separation and double quotes as values delimiter.

查看更多
forever°为你锁心
3楼-- · 2019-09-06 02:08

Try This

$file = "FNAC_SPECTACLES.csv";
$handle = fopen($file, "r");
$row = 1;
while (($data = fgetcsv($handle, 0, ";","'")) !== FALSE) 
{
    if($row == 1)
    {
        // skip the first row   
    }
    else
    {
        echo "<pre>";
        print_r($data);
    }
    $row++;
}

fgetcsv() in third argument in separator to you want to save in csv file. Ex: comma,semicolon or etc..

查看更多
登录 后发表回答