Home >Backend Development >PHP Tutorial >How Can I Parse a CSV File in PHP, Handling Commas and Missing Fields?
How to Parse a CSV File Using PHP
Question:
Given a CSV file with content like:
"text, with commas","another text",123,"text",5; "some without commas","another text",123,"text"; "some text with commas or no",,123,"text";
How can you parse this file using PHP?
Answer:
To parse the CSV file in PHP, you can utilize the fgetcsv function.
Code:
$row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); }
This code reads the CSV file line by line and prints the values of each field in the CSV columns.
The above is the detailed content of How Can I Parse a CSV File in PHP, Handling Commas and Missing Fields?. For more information, please follow other related articles on the PHP Chinese website!