在新行上使用str_getcsv解析CSV失败

xmq68pz9  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(165)

当用PHP阅读CSV文件时,CSV文件中的换行符出现问题。如果逗号后面跟着换行符,则一个单元格的内容将被拆分:

$csv = array_map('str_getcsv', file($file));

first,second,"third,
    more,text","forth"
next,dataset

这将导致:

1) first | second | third
2) more text | forth
3) next | dataset

虽然它应该导致:

1) first | second | third more text | forth
2) next | dataset

这是str_getcsv中的一个错误吗?

ki0zmccv

ki0zmccv1#

请不要这样做,使用fgetcsv(),因为file()不关心文件中的字符串封装。

$fh = fopen('file.csv', 'r');

while( $line = fgetcsv($fh) ) {
    // do a thing
}

fclose($fh);

https://secure.php.net/manual/en/function.fgetcsv.php
如果可以的话,在执行操作之前,尽量不要将所有行存储到一个数组中,这样系统的内存使用率就会提高。

ctehm74n

ctehm74n2#

<?php

$csvString = "ID,Condition,Condition,Condition,Condition,AdSize,Content:Text,Content:Text,Content:Text,Content:ImageUrl,Content:LandingPageUrl,Archive,Default
ID,Locations:Region,Device Properties:Device,Weather:Condition,Dmp:Liveramp,AdSize,title1,description1,price1,imageUrl1,landingPageUrl1,Archive,Default
ROW_001,\"Wa, Ca, Tn\",Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/Snow.jpg,https://www.example.com,TRUE,
ROW_002,Wa,Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/New_Snow.jpg,https://www.example.com,,
ROW_003,Wa,Mobile,,,300x250,Hello Washingtonian,My Custom Description,10,http://domain/clear.jpg,https://www.example.com,,
ROW_004,,,,,300x250,Hello,My Custom Description,20,http://domain/clear.jpg,https://www.example.com,,TRUE";

function csvToArray($csvString, $delimiter = ',', $lineBreak = "\n") {
    $csvArray = [];
    $rows = str_getcsv($csvString, $lineBreak); // Parses the rows. Treats the rows as a CSV with \n as a delimiter
    foreach ($rows as $row) {
        $csvArray[] = str_getcsv($row, $delimiter); // Parses individual rows. Now treats a row as a regular CSV with ',' as a delimiter
    }
    return $csvArray;
}

print_r(csvToArray($csvString));

相关问题