How to parse a CSV File in PHP?

Configurare noua (How To)

Situatie

The following approach will be utilized to parse the CSV File using PHP, which is described below:

Solutie

Pasi de urmat

Add data to an Excel file. The following example is given for sample data having Name and Coding Score as their column headers.

Convert to CSV file by following the path. Go to File>Export>Change File Type> CSV Type. Save the file in your working folder with the name “Book1.csv”.

Steps for Parsing CSV file using PHP:

Step 1. Create a folder and add that CSV file and create a new PHP file in it

Step 2. Open the PHP file and write the following code in it which is explained in the following steps.

  • Open dataset of CSV using fopen function.
  • Read a line using fgetcsv() function.
  • Use a loop to iterate in every row of data.
  • lose that file using PHP fclose() method.
<?php
if (($open = fopen(“Book1.csv”, “r”)) !== false) {
while (($data = fgetcsv($open, 1000, “,”)) !== false) {
$array[] = $data;
}
fclose($open);
}
echo “<pre>”;
// To display array data
var_dump($array);
echo “</pre>”;
?>

Tip solutie

Permanent

Voteaza

(11 din 19 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?