Home >Backend Development >PHP Tutorial >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);
In this code:
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
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!