使用PHP处理cvs文件中的特殊字符

时间:2016-03-14 22:19:27

标签: php csv character

我想使用PHP函数“fgetcsv”来读取CSV文件并将一些元素存储在数组中,以便以后使用它们。问题是我的文件有点奇怪:

Date,From,To,"Dep time","Arr time",Duration
2012-04-06,"Abu Dhabi / Abu Dhabi (AUH/OMAA)","Brussels / Brussels (BRU/EBBR)",09:18:00,14:12:00,07:54:00

所以从我所看到的,当一个名字由几个单词组成时,会出现一些“”。知道怎么处理吗?

1 个答案:

答案 0 :(得分:1)

I believe you're talking about the fact that some of the elements in the .csv are enclosed by quotes? PHP has a built in function for reading CSV data. See more information here... http://php.net/manual/en/function.fgetcsv.php

EDIT: I should clarify. The fgetcsv() function will handle the enclosure for you. If you'd like, you can specify a different character other than the default of double quote.

EXAMPLE:

$fileHandle = fopen('/path/to/file.csv', "r");
while (($data = fgetcsv($fileHandle, 1000, ",")) !== FALSE) {
      // $data is now an array of a line from your file, each loop will go to the next line
      print_r($data); // will show you the array from each line of the file
      echo "<br>";
}
fclose($fileHandle);