将CSV转换为PHP数组-结束行出现问题(CR LF) [英] Converting CSV to PHP Array - issue with end line (CR LF)

查看:84
本文介绍了将CSV转换为PHP数组-结束行出现问题(CR LF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将csv文件转换为数组.但是,问题在于该行的末尾是 CR LF ,并且未被检测到,因此数组具有错误的偏移量. CR LF被忽略,并且周围的单元格"被合并.

I am converting csv file to an array using code bellow. But, problem is that end of the row is CR LF, and it is not detected, so array has wrong offset. CR LF is ignored and "cells" around it are merged.

我该如何重写代码以正确检测到此行结尾并拆分数组?还是有更好的方法将csv转换为数组?

How could i rewrite code to detect this row ending and split array correctly ? Or, is there better approach to convert csv to array?

这里有一些类似的问题,但是我还没有找到解决这个问题的方法.

There are some simmilar questions here but i have not found solution to this issue yet.

谢谢.

$fileName ='test.csv';   
$csvData = file_get_contents($fileName); 
$csvNumColumns = 11; 
$csvDelim = ";"; 
$data = array_chunk(str_getcsv($csvData, $csvDelim), $csvNumColumns); 

print_r($data);

推荐答案

您是否尝试过使用fgetcsv()? php.net 上的完整信息.

Have you tried using fgetcsv()? full info on php.net.

php.net的用法示例

Example usage from php.net

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

这篇关于将CSV转换为PHP数组-结束行出现问题(CR LF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆