0

我在 CSV 文件中有数据。我需要读取文件并将数据放入数组中。我的 CSV 文件中有 5 列,如下所示:

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

MARGHERITA  | Tomato, Cheese, Oregano   | $7.00 | $11.00 | $13.00
  1. 我怎样才能把explode()它变成数组?如果我使用逗号将其分解为数组,它将变为CAPRICCIOA - Tomato - Cheese因为我的文本已经有逗号。

  2. 如何将其拆分为不同的行,例如 MySQL,以便循环查看结果?

我尝试了以下方法:

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

3 回答 3

6

如何使用 PHP 函数:fgetcsv()

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

于 2012-12-15T04:32:28.333 回答
2

你应该转向 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

于 2012-12-15T04:33:36.330 回答
0

试试这个:

$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>';
}
于 2012-12-15T09:23:47.023 回答