Asked 7 years ago
28 Feb 2017
Views 1224
noob

noob posted

how to parse csv in php ?

try to prase the csv and store to database.

$csv=file_get_content("file.csv");
$data=explode(",",$csv);


i am exploding it csv content with "," and still i getting improper result.

so is that good way to parse beside of it ?
Rasi

Rasi
answered Nov 30 '-1 00:00

fgetcsv is the function which help to get csv content ,


function parseCsv($filename){
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $cSvdata[]=$data;
        $row++;
    }
    fclose($handle);
    return $cSvdata;
}
}
parseCsv("user.csv");

here

fgetcsv($handle, 1000, ",")
first argument - file resource
second argument (optional) - max length of line to be get parsed
third argument (optional) - delimiter

fgetcsv — Gets line from file pointer and parse for CSV fields
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

fgets also used to read the csv

fgets read the line from the current file pointer . and then explode the line by comma separator by explode function .


function readCsv($filename){
$row = 1;
if (($handle = fopen($filename, "r")) !== FALSE) {
    while (($line = fgets($handle, 1000, ",")) !== FALSE) {
        $data=explode(",",$line);
        $cSvdata[]=$data;
        $row++;
    }
    fclose($handle);
    return $cSvdata;
}
}
readCsv("user.csv");

readcsv function here read the csv file and give use output in array format
Post Answer