How To Read In A CSV File Using PHP

To read in a CSV file in PHP, you can use the built-in fopen() and fgetcsv() functions. Here’s an example of how to use them:

<?php
// specify the path to the CSV file
$csv_file = "path/to/file.csv";

// open the CSV file for reading
$file_handle = fopen($csv_file, "r");

// loop through each line of the CSV file
while (($data = fgetcsv($file_handle)) !== false) {
    // do something with the data from each line
    // $data is an array of values from the current line
    echo "Name: " . $data[0] . "<br>";
    echo "Email: " . $data[1] . "<br>";
}

// close the file handle
fclose($file_handle);
?>

In this example, we’re specifying the path to the CSV file and opening it for reading with fopen(). We then loop through each line of the file with a while loop and use fgetcsv() to retrieve an array of values from the current line. We can then do something with the data from each line, such as printing it out. Finally, we close the file handle with fclose(). Note that the delimiter used in the CSV file (e.g. comma, semicolon, tab) should be specified as the second argument to fgetcsv().

Leave a Reply

Proudly powered by WordPress | Theme: Code Blog by Crimson Themes.