
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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>\n"; $row_count++; for ($counter=0; $counter < $data_count; $counter++) { echo $$data_in_csv[$counter] . "<br />\n"; } } 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 Questions & Answers
- How to import csv file in PHP?
- How to convert JSON file to CSV file using PowerShell?
- 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?
- 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?
- Reading and Writing CSV File using Python
- Writing a Pandas DataFrame to CSV file
- How to create a CSV file manually in PowerShell?
- How to create a blank csv file in R?
Advertisements