本文介绍了PHP CSV 字符串到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 CSV 字符串解析为 PHP 中的数组.CSV 字符串具有以下属性:

I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:

Delimiter: ,
Enclosure: "
New line:

示例内容:

"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"

当我尝试像这样解析它时:

When I try to parse it like this:

$url = "http://www.url-to-feed.com";
$csv = file_get_contents($url);
$data = str_getcsv($csv);
var_dump($data);

最后一个元素和第一个元素连接成一个字符串:

The last and first element are concatenated in one string:

[0]=> string(5) "12345"
...
[7]=> string(4) "0.04"
[8]=> string(19) "27-05-2013
"12346""

我该如何解决这个问题?任何帮助将不胜感激.

How can I fix this? Any help would be appreciated.

推荐答案

这样做:

$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);

它会给你这样的输出:

Array
(
    [0] => Array
        (
            [0] => 12345
            [1] => Computers
            [2] => Acer
            [3] => 4
            [4] => Varta
            [5] => 5.93
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

    [1] => Array
        (
            [0] => 12346
            [1] => Computers
            [2] => Acer
            [3] => 5
            [4] => Decra
            [5] => 5.94
            [6] => 1
            [7] => 0.04
            [8] => 27-05-2013
        )

)

希望对大家有所帮助.

这篇关于PHP CSV 字符串到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:20