2012-12-15 136 views
0

我有CSV文件中的數據。我需要讀取文件並將數據放入數組中。我在我的CSV文件5列,就像這樣:PHP爆炸爲CSV?

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); 
+1

CSV是逗號分隔的,除非有一個字段的值,在這種情況下,整個字段值被包含在雙引號逗號。你應該通過文本並解析或寫一個正則表達式來提取。使用explode()你說的方式在這裏不起作用,因爲你需要做更多的事情。 – Anton

+0

可能是[分割CSV,但不能在逗號(PHP)上重複?](http://stackoverflow.com/questions/11683284/splitting-csv-but-not-on-comma-only-php) –

回答

1

您應該轉向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

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