49K Views

Working with CSV files in PHP/Symfony

Updated 21 November 2017

Facebook Linkedin

CSV files are widely used in data export, import. Here, I am going to describe how to work with CSV file(s) in PHP or Symfony. Blog also mentions the use of BOM in CSV files for interoperability in Excel.

What are CSV files?

According to Wikipedia,  comma-separated values (CSV) file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas.

As clear by name, Each CSV file record contains values separated by comma like
John,Harry,Sejal

(,) is used as the separator

UTF-8 CSV file for Excel:

If we want CSV file to be recognized by excel software. Then we should use BOM for CSV file also.

Although BOM (byte order mark is optional for CSV files), it could be used for interoperability.

BOM for CSV can be generated in PHP/Symfony as

Read more

Reading CSV files

Since CSV files provide the easiest way to save Tabular data. so, they are often used for Uploading data or other purposes.

PHP provides inbuilt function fgetcsv for reading CSV files. We could use fgetcsv like in example below
Example:

Writing CSV files

Unlike, fgetcsv PHP provides inbuilt function fputcsv for Writing CSV files.

Example:

We can also download CSV file instead of directly writing it,

We could do so by writing to PHP Output Stream.

We will need to set headers to download CSV file using this method instead of viewing it as String

Setting headers to download file

In PHP:

In Symfony:

What’s More?

That’s all for now. Feel free to comment or ask any question about working with CSV.

Category(s) Symfony
. . .

Leave a Comment

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


2 comments

  • bklv
    well done! thanks
    • Vidushi Singh (Moderator)
      Thank you so much for appreciation!!