
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
How to parse a CSV file using PHP
To parse a CSV file in PHP, the code is as follows. Under fopen(), set the path of the .csv file−
Example
$row_count = 1; if (($infile = fopen("path to .csv file", "r")) !== FALSE) { while (($data_in_csv = fgetcsv($infile, 800, ",")) !== FALSE) { $data_count = count($data_in_csv); echo "<p> $data_count in line $row_count: <br /></p>
"; $row_count++; for ($counter=0; $counter < $data_count; $counter++) { echo $$data_in_csv[$counter] . "<br />
"; } } fclose(infile); }
Code explanation − The file can be opened in reading mode (if it exists) and until a specific threshold length, it can be read and displayed. The row_count counter can be incremented to parse the next line in the file.
Output
The input CSV file will be parsed and displayed line by line.
For PHP version>=5.3.0, the below code can be used−
$file_to_read = file('path to .csv file'); $data_to_ingest = []; foreach ($file_to_read as $infile) { $data_to_ingest[] = str_getcsv(infile); }
Note − This wouldn’t work if the CSV file has any new line characters since the logic is that the function splits the newlines and doesn’t identify quotation marks.
- Related Articles
- How to import csv file in PHP?
- How to convert JSON file to CSV file using PowerShell?
- How to convert CSV File to PDF File using Python?
- How to edit the CSV file using PowerShell?
- How to retrieve CSV file headers using PowerShell?
- How to append data into a CSV file using PowerShell?
- How to save a matrix as CSV file using R?
- How to convert JSON to CSV file using PowerShell?
- How to read data from *.CSV file using JavaScript?
- Create a GUI to convert CSV file to Excel file using Python
- How to read and parse CSV files in C++?
- Writing a CSV file in Java using OpenCSV
- How to save a Python Dictionary to CSV file?
- How to create a CSV file manually in PowerShell?
- How to create a blank csv file in R?

Advertisements