gpt4 book ai didi

PHP CSV 字符串到数组

转载 作者:IT王子 更新时间:2023-10-29 00:59:33 33 4
gpt4 key购买 nike

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

Delimiter: ,
Enclosure: "
New line: \r\n

示例内容:

"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"

当我尝试这样解析它时:

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

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

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

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

最佳答案

这样做:

$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 字符串到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17761172/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com