How to Read a CSV File in PHP?

03-Apr-2023

.

Admin

How to Read a CSV File in PHP?

Hi Dev,

This tutorial shows you how to read a csv file in php?. We will look at example of php open and read csv file. you can see read a csv file in php example. This article will give you simple example of php open and read csv file. Let's see bellow example csv file to read in php.

in this example, we will use fopen(), fgetcsv() and fclose() to read a csv file. The fgetcsv() function can parse a line from an open file and check for CSV fiel.Let's see both examples with output.

Example : read csv file


index.php

<?php

// csv file open

if (($open = fopen("sample.csv", "r")) !== FALSE)

{

// csv file convert to array

while (($data = fgetcsv($open, 1000, ",")) !== FALSE)

{

$array[] = $data;

}

// file close

fclose($open);

}

//To display data

echo "<pre>";

print_r($array);

echo "</pre>";

?>

Output:

Array

(

[0] => Array

(

[0] => 1

[1] => Hardik Savani

[2] => hardik@gmail.com

)

[1] => Array

(

[0] => 2

[1] => Jaydeep Pathar

[2] => jaydeep@gmail.com

)

[2] => Array

(

[0] => 3

[1] => Nikhil Thummer

[2] => nikhil@gmail.com

)

)

I hope it could help you...

#PHP