fgetcsv(f_pointer,int $length,string $delimiter, string $encloser,string $escape);
| Parameter | DESCRIPTION |
|---|---|
| f_pointer | Required : a successful file pointer fopen() |
| $length | Optional : Must be greater than the maximum line length |
| $delimiter | Optional : One char only |
| $encloser | Optional : Field encloser char |
| $escape | Optional : escape parmeter sets the escape char |
<?php
$f_pointer=fopen("student.csv","r"); // file pointer
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
echo print_r($ar); // print the array
echo "<br>";
}
?>
We used open the csv file and keep the pointer
$f_pointer=fopen("student.csv","r"); // file pointer
We will use our student table csv data. ( Download a copy of student.csv file at end of this tutorial ) Array ( [0] => 1 [1] => John Deo [2] => Four [3] => 75 [4] => female )
Array ( [0] => 2 [1] => Max Ruin [2] => Three [3] => 85 [4] => male )
Array ( [0] => 3 [1] => Arnold [2] => Three [3] => 55 [4] => male )
Array ( [0] => 4 [1] => Krish Star [2] => Four [3] => 60 [4] => female )
Array ( [0] => 5 [1] => John Mike [2] => Four [3] => 60 [4] => female )
Array ( [0] => 6 [1] => Alex John [2] => Four [3] => 55 [4] => male )
You can read how the CSV data is prepared from the student table here. <?php
$f_pointer=fopen("student.csv","r"); // file pointer
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
$sql="INSERT INTO student(id,name,class,mark,sex)values('$ar[0]','$ar[1]','$ar[2]','$ar[3]','$ar[4]')";
echo $sql;
echo "<br>";
}
?>
Part of the output is here
INSERT INTO student(id,name,class,mark,sex)values('1','John Deo','Four','75','female')
INSERT INTO student(id,name,class,mark,sex)values('2','Max Ruin','Three','85','male')
INSERT INTO student(id,name,class,mark,sex)values('3','Arnold','Three','55','male')
INSERT INTO student(id,name,class,mark,sex)values('4','Krish Star','Four','60','female')
<?php
$f_pointer=fopen("student.csv","r"); // file pointer
$first_line="T";
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
if($first_line<>'T'){
$sql="INSERT INTO student(id,name,class,mark,sex)values('$ar[0]','$ar[1]','$ar[2]','$ar[3]','$ar[4]')";
echo $sql;
echo "<br>";
}
$first_line='F';
}
?>
If you want the sql file to be downloaded then follow the instruction at the end of CSV file creation.
fputcsv(): to write data to a csv file
student.csv
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.