Parse CSV file in PHP and retrieve contents

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>”;
}
}

 

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in PhP, Tools and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s