Benjamin W
Benjamin W

Reputation: 2848

PHP explode for CSV?

I have data in a CSV file. I need to read the file and put the data into an array. I have 5 columns in my CSV file, like this:

CAPRICCIOSA | Tomato, Cheese, Mushrooms | $8.00 | $12.00 | $15.00

MARGHERITA  | Tomato, Cheese, Oregano   | $7.00 | $11.00 | $13.00
  1. How can Iexplode() it into array? If I use a comma to explode it into array, it will become CAPRICCIOA - Tomato - Cheese because my text already has a comma.

  2. How can I split it into different rows, like MySQL so I can loop through the results?

I have tried the following:

 $file="dish.csv" ;
 $file=file_get_contents($file);
 $array=explode(",", $file);

Upvotes: 0

Views: 13579

Answers (3)

Kasper DK
Kasper DK

Reputation: 557

Try this:

$fn='dish.csv';

$file_array = file($fn);
foreach ($file_array as $line_number =>&$line)
{
    //$line=utf8_encode($line);
    $row=explode('|',$line);

    echo 'Dish: '.$row[0].'<br>';
    $ingredients=explode(',',$row[1]);
    echo 'Ingredients:';
    echo '<pre>';
    print_r($ingredients);
    echo '<br><br>';
    echo '</pre>';
}

Upvotes: 0

Yagi
Yagi

Reputation: 511

How about using PHP function : fgetcsv()

http://php.net/manual/en/function.fgetcsv.php

Upvotes: 6

cheesemacfly
cheesemacfly

Reputation: 11762

You should turn to fgetcsv:

<?php
$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);

?>

http://php.net/manual/en/function.fgetcsv.php

Upvotes: 2

Related Questions