Home > Backend Development > PHP Tutorial > How to Parse CSV Files with Embedded Commas in PHP Using fgetcsv?

How to Parse CSV Files with Embedded Commas in PHP Using fgetcsv?

Linda Hamilton
Release: 2024-11-24 14:31:44
Original
894 people have browsed it

How to Parse CSV Files with Embedded Commas in PHP Using fgetcsv?

Creating Arrays from CSV Files with PHP Using fgetcsv

Question:

A user wants to create arrays from a CSV file using the fgetcsv function. However, their current code is malfunctioning when a field contains multiple commas, such as addresses. They also lack access to str_getcsv. Can we provide a solution?

Answer:

Using fgetcsv to Parse CSV Files

As mentioned in the title, fgetcsv is an excellent option for parsing CSV files. It offers an efficient way to break down each line into an array of elements.

Here's a code snippet that utilizes fgetcsv:

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  print_r($line);
}
fclose($file);
Copy after login

In this code:

  • fopen(): Opens the CSV file for reading and assigns it to a file handle.
  • while loop: Iterates through each line of the file until the end of the file is reached, determined by the FALSE return of fgetcsv().
  • fgetcsv(): Parses the current line into an array of elements, which is then printed.
  • fclose(): Closes the file handle.

Handling Embedded Commas

To handle fields with embedded commas, we need to ensure that the CSV file is properly formatted with appropriate delimiters or quotation marks. By enclosing fields with double quotes, fgetcsv can correctly identify and separate elements containing commas.

For instance, the following CSV file format would work corretamentely:

Scott L. Aranda,"123 Main Street, Bethesda, Maryland 20816",Single
Todd D. Smith,"987 Elm Street, Alexandria, Virginia 22301",Single
Edward M. Grass,"123 Main Street, Bethesda, Maryland 20816",Married
Aaron G. Frantz,"987 Elm Street, Alexandria, Virginia 22301",Married
Ryan V. Turner,"123 Main Street, Bethesda, Maryland 20816",Single
Copy after login

The above is the detailed content of How to Parse CSV Files with Embedded Commas in PHP Using fgetcsv?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template