Php 将CSV转换为阵列

Php 将CSV转换为阵列,php,arrays,csv,fgetcsv,Php,Arrays,Csv,Fgetcsv,我有一个带有机场代码和城市名称的阵列(大约3500行) 我需要将该文件转换为php数组。这是我目前的代码: if(($handle = fopen('test.csv', 'r')) !== FALSE) { while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) { echo '<pre>'; print_r($data); echo '<

我有一个带有机场代码和城市名称的阵列(大约3500行)

我需要将该文件转换为php数组。这是我目前的代码:

if(($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {
        echo '<pre>';
            print_r($data);
            echo '</pre>';
    }
    fclose($handle);
}

如果是换行符,您可以尝试以下暴力方法:

ini_set('auto_detect_line_endings', TRUE);/// (PHP's detection of line endings) write at the top.


$csvrows = array_map('str_getcsv', file($filepath));
$csvheader = array_shift($csvrows);
$csv = array();
foreach ($csvrows as $row) {
   $csv[] = array_combine($csvheader, $row);
}
PHP5.3提供,或作为手册中的解决方法,通过或提供

试试这个:-

$csv = array();

if (($file = fopen('test.csv', 'r')) === false) {
    throw new Exception('There was an error loading the CSV file.');
} else {  
   while (($line = fgetcsv($file, 1000)) !== false) {
      $csv[] = $line;
   }
   fclose($handle);
}
试一试-


你确定这些是
字符,而不是微软喜欢到处散布的花哨的66和99字符吗?对我来说很好。可能是你的
PHP\u版本中的一个bug(是哪个?)。或者试试
var\u dump(数组映射(“str\u getcsv”,file($fn)))
@StefanPantke:既然你提到了它,他只从中得到了一条记录。因此,换行符不被识别,因此引号也被误解。另请参见php.ini设置
自动检测行结尾
@StefanPantke:
1
只是
打印的结果
在打印后由
echo
写入的文件本身已经抛出了输出(为什么它也不在pre标签中)。非常好,这解决了我的问题。非常感谢非常感谢你+1也为未知的升级PHP!!
$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);
ini_set('auto_detect_line_endings', TRUE);/// (PHP's detection of line endings) write at the top.


$csvrows = array_map('str_getcsv', file($filepath));
$csvheader = array_shift($csvrows);
$csv = array();
foreach ($csvrows as $row) {
   $csv[] = array_combine($csvheader, $row);
}
$csv = array();

if (($file = fopen('test.csv', 'r')) === false) {
    throw new Exception('There was an error loading the CSV file.');
} else {  
   while (($line = fgetcsv($file, 1000)) !== false) {
      $csv[] = $line;
   }
   fclose($handle);
}