fgetcsv()在将.csv文件转换为数组时不考虑换行符

pbwdgjma  于 2023-06-03  发布在  其他
关注(0)|答案(4)|浏览(528)

我有一个包含机场代码和城市名称的数组(大约3500行)。

code,city
"Abilene, TX ",ABI
"Adak Island, AK ",ADK
"Akiachak, AK ",KKI
"Akiak, AK ",AKI
"Akron/Canton, OH ",CAK
"Akuton, AK ",KQA
"Alakanuk, AK ",AUK
"Alamogordo, NM ",ALM

我需要把这个文件转换成一个PHP数组。这是我目前为止的代码:

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

虽然我为fgetcsv函数设置了分隔符和包围字符,但结果如下:

Array
(
    [0] => code
    [1] => city
"Abilene
    [2] => TX "
    [3] => ABI
"Adak Island
    [4] => AK "
    [5] => ADK
"Akiachak
    [6] => AK "
    [7] => KKI
"Akiak
    [8] => AK "
    [9] => AKI
"Akron/Canton
    [10] => OH "
    [11] => CAK
"Akuton
    [12] => AK "
    [13] => KQA
"Alakanuk
    [14] => AK "
    [15] => AUK
"Alamogordo
    [16] => NM "
    [17] => ALM
)
lymnna71

lymnna711#

如果是换行符,你可以尝试使用蛮力方法:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);

str_getcsv可在PHP 5.3中使用,或者作为手册中的解决方法,通过upgradephpPHP_Compat使用。

tvokkenx

tvokkenx2#

试试这个:-

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);
}
atmip9wb

atmip9wb3#

尝试-

$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);
}
u1ehiz5o

u1ehiz5o4#

要解决这个问题,可以尝试在用fgetcsv解析每行之前删除其中的空格。

if (($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($line = fgets($handle)) !== FALSE) {
        $line = trim($line); // Trim whitespace from the line
        $data = str_getcsv($line, ',', '"'); // Parse CSV data
        
        echo '<pre>';
        print_r($data);
        echo '</pre>';
    }
    fclose($handle);
}

在更新后的代码中,我们使用fgets读取文件的每一行,然后进行修剪以删除任何前导或尾随空格。最后,使用str_getcsv解析CSV数据。

相关问题