PHP CSV 字符串到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17761172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP CSV string to array
提问by Tomzie
I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:
我正在尝试将 CSV 字符串解析为 PHP 中的数组。CSV 字符串具有以下属性:
Delimiter: ,
Enclosure: "
New line: \r\n
Example content:
示例内容:
"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.
我怎样才能解决这个问题?任何帮助,将不胜感激。
回答by saran banerjee
Do this:
做这个:
$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
print_r($array);
It will give you an output like this:
它会给你一个这样的输出:
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
)
)
I hope this can be of some help.
我希望这会有所帮助。
回答by Gaui
Handy oneliner:
方便的单线:
$csv = array_map('str_getcsv', file('data.csv'));
回答by iateadonut
You should use fgetcsv.Since you cannot import a file as a stream because the csv is a variable, then you should spoof the string as a file by using php://temp
or php://memory
first:
您应该使用 fgetcsv。由于您无法将文件作为流导入,因为 csv 是一个变量,因此您应该首先使用php://temp
或将字符串伪装为文件php://memory
:
$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);
Then you will have no problem using fgetcsv:
那么你使用 fgetcsv 就没有问题了:
$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
$csv[] = $data;
}
$data
will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.
$data
将是单个 csv 行的数组(可能包括换行符或逗号等),因为它应该是。
回答by Rajen K Bhagat
I have used following function to parse csv string to associative array
我使用以下函数将 csv 字符串解析为关联数组
public function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ',', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
如果您的 csv 文件名是 mycsv.csv 则您将此函数调用为:
$dataArray = csvToArray(mycsv.csv);
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/
您也可以在http://www.scriptville.in/parse-csv-data-to-array/ 中获取此脚本
回答by Joseph D.
A modification of previous answers using array_map
.
Blow up the CSV data with multiple lines.
使用array_map
.
用多行炸毁 CSV 数据。
$csv = array_map('str_getcsv', explode("\n", $csvData));
回答by user
Slightly shorter version, without unnecessary second variable:
略短的版本,没有不必要的第二个变量:
$csv = <<<'ENDLIST'
"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"
ENDLIST;
$arr = explode("\n", $csv);
foreach ($arr as &$line) {
$line = str_getcsv($line);
}
回答by Ramsés Fernández
If you need a name for the csv columns, you can use this method
如果需要 csv 列的名称,可以使用此方法
$example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));
回答by Stacey Richards
If you have carriage return/line feeds within columns, str_getcsv will not work.
如果列中有回车/换行符,则 str_getcsv 将不起作用。
Try https://github.com/synappnz/php-csv
试试https://github.com/synappnz/php-csv
Use:
用:
include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
// do something with $row
}
回答by formedya
You can convert CSV string to Array with this function.
您可以使用此功能将 CSV 字符串转换为数组。
function csv2array(
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
) {
$arr = array_map(
function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
if ($FirstLineTitle && !$FirstLine) {
$FirstLine = explode( $delimiter, $result[0] );
}
$lineResult = array_map(
function ( $field ) {
return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
},
$trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
);
return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
},
($result = preg_split(
$skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
preg_replace_callback(
'/"(.*?)"/s',
function ( $field ) {
return urlencode( utf8_encode( $field[1] ) );
},
$enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
)
))
);
return $FirstLineTitle ? array_splice($arr, 1) : $arr;
}
回答by Ahmad Al- Hashlamoun
Try this, it's working for me:
试试这个,它对我有用:
$delimiter = ",";
$enclosure = '"';
$escape = "\" ;
$rows = array_filter(explode(PHP_EOL, $content));
$header = NULL;
$data = [];
foreach($rows as $row)
{
$row = str_getcsv ($row, $delimiter, $enclosure , $escape);
if(!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}