Parse CSV File in PHP and Retrieve Contents

Posted on the 04 May 2012 by Akahgy

Description:

Retrieve CSV file contents in PHP.

Solution:

The parsing is done in 2 steps. First read the .csv file:

$handle = fopen(“file.csv”, “r”);
$csv = array();
while(($data = fgetcsv($handle)) !== FALSE) {
// get the values from the csv
$csv[] = $data[0];
}
fclose($handle);

Then iterate rows, skipping the title row and explode the row string into row values:

if ($csv) {
for ($i=1; $i<=count($csv); $i++) {
$row = $csv[$i];
$row_values = explode(‘;’, $row);
print_r($row_values);
echo “<br>”;
}
}