Home > Backend Development > PHP Tutorial > How Can I Parse a CSV File in PHP, Handling Commas and Missing Fields?

How Can I Parse a CSV File in PHP, Handling Commas and Missing Fields?

Susan Sarandon
Release: 2024-12-09 01:24:10
Original
356 people have browsed it

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"; 
Copy after login

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);
}
Copy after login

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!

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