Home >Backend Development >PHP Tutorial >How Can I Parse CSV Data in PHP Using `fgetcsv()`?

How Can I Parse CSV Data in PHP Using `fgetcsv()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 17:59:10426browse

How Can I Parse CSV Data in PHP Using `fgetcsv()`?

Parsing CSV Data in PHP

This question addresses the issue of parsing a CSV file into its constituent elements using PHP. The example provided contains a CSV file with textual and numerical values, including commas and missing data.

Solution:

PHP provides the fgetcsv() function specifically designed for parsing CSV files. Here's how you can accomplish the parsing:

$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 script leverages fgetcsv() to retrieve data from the CSV file, one line at a time. It maintains a count of fields per line and iterates through them, printing out each field on its own line.

By utilizing this method, you can effortlessly parse and manipulate the data in your CSV file within PHP.

The above is the detailed content of How Can I Parse CSV Data in PHP Using `fgetcsv()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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