Back to Top

To parse CSV Data in PHP

To parse CSV Data in PHP

Sometimes you have data(mainly MySQL data) in comma-separated values (CSV) format. or you have CSV file to import database values and you tried with CSV format from PHPMyAdmin and sometimes its giving error so you need to write some script to import a data So you can go with fgetcsv function.

If the CSV data is in a file or get via a URL so You can open the file with fopen( ) and read in
the data with fgetcsv() function in PHP. With the use of fgetcsv(), you can get CSV data in HTML or PHP.fgetcsv() function is to gets line from file pointer(fp) and parsing a CSV fields.

What is fgetcsv:

fgetcsv() function gets file pointer line and parse for CSV fields.This function is similar to fgets () function. fgetcsv() function stops to return to a new line when it reaches the end of the specified length or read the End of the file (EOF).

First Parameter refers to the file pointer.

The second argument to fgetcsv() is the length of file and it must be longer than the maximum length of a line in your CSV file.length of file is a semi-optional parameter of fgetcsv.

NOTE: Don’t forget to count the end-of-line white-space.

The third argument in fgetcsv() is optional, it’s used when you want to pass different delimiter instead of the comma(,).

Let’s see one example:

You have a file exported from Excel or a database, and you want to extract the records and fields into a format you can manipulate in PHP and want to import it in Database.

Must READ:
To import user from CSV in WordPress
Parsing a RSS Feed with WordPress

You know that is a comma-delimited CSV file is a plain text file consisting of characters, you can use excel to open, the effect is the same as with an xls table.Above example will read the CSV data from sample.CSV file and fetch all data one by one.First connect to MySQL and update record to the database.

Above example give you a basic idea to extract CSV data and import it in the database with Script.

Comments (2)

  1. To parse CSV Data in PHP…

    Sometimes you have data(mainly MySQL data) in comma-separated values (CSV) format. or you have CSV file to import database values and you tried with CSV format from PHPMyAdmin and sometimes its giving error so you need to write some script to import a …

    1. Really basic and clean post. I liked your post syetls. You explain all things on article and everybody i guess got it. Keep it bro

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

MySQL coalesce() function

Posted on 6 years ago

Bhumi

Learn ElasticSearch in 10 Minutes

Posted on 2 years ago

Bhumi

How to Create a Custom WordPress Widget

Posted on 5 years ago

Bhumi