Search code examples
phpcsvfgetcsv

Problem with .csv file and missed comma(s)


Hi all I have a problem with CSV opening through PHP code. My PHP code is:

<?php
header("Content-Type: text/html; charset=windows-1251");

echo "<html>
<head>
    <title></title>
</head>
<body>
";

$file = "import.csv";

if(file_exists($file)) {
    if (($fopen = fopen($file, "r")) !== FALSE) {
        echo "<table>\n";
        while (($data = fgetcsv($fopen, 1024, ",")) !== FALSE) {
            $max = count($data);
            $num++;
            echo "<tr>\n<td>".$num."</td>\n";
            for ($i=0;$i<$max;$i++) {
                echo "<td>".$data[$i]."</td>\n";
            }
            echo "</tr>\n";
        }
        echo "</table>";
        fclose($fopen);
    }
}
else {
    echo "File doesn't exists!";
}

echo "
</body>
</html>";
?>

The problem isn't in PHP code, the problem is in .csv file. PHP code must work even if there is missing comma, when it show the information the normal way.

The .csv file:

First name,Family,Sex,Date of birth,City,Phone number
One, Ofamily, Male, 1975, LA,13-25-16
Two, Tfamily, Male, 1955, LV, 555-14345
Three, Thfamily, Male, 1958, NY, 15689
Four, Ffamily, Female, 1974, SF, 5897912
Five, Fifamily, Male, 1991, LA, 123456789
Six, Sfamily, Male, 1967, 9876542
Seven, Sefamily, Female,, SF, 

Solution

  • <?php
    header("Content-Type: text/html; charset=windows-1251");
    
    echo "<html>
    <head>
        <title></title>
    </head>
    <body>
    ";
    
    $file = "import.csv";
    
    if(file_exists($file)) {
        if (($fopen = fopen($file, "r")) !== FALSE) {
            echo "<table>\n";
            while (($data = fgetcsv($fopen, 1024, ",")) !== FALSE) {
                $num++;
                echo "<tr>\n<td>".$num."</td>\n";
                foreach($data as $k => $v) {
                    switch ($k) {
                        case 0 : // first name
                        case 1 : // family
                        case 2 : // sex
                        case 4 : // city
                            if (is_numeric($v)) {
                                array_splice($data,$k,0,'');
                            }
                            break;
                        case 3 : // date of birth
                        case 5 : // phone number
                            if (!is_numeric($v)) {
                                array_splice($data,$k,0,'');
                            }
                            break;
                    }
                }
                foreach($data as $v) {
                    echo "<td>".$v."</td>\n";
                }
                echo "</tr>\n";
            }
            echo "</table>";
            fclose($fopen);
        }
    }
    else {
        echo "File doesn't exists!";
    }
    
    echo "
    </body>
    </html>";
    ?>