PHP的CSVstring到数组
我试图parsing一个CSVstring到PHP中的数组。 CSVstring具有以下属性:
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"
当我试图parsing它是这样的:
$url = "http://www.url-to-feed.com"; $csv = file_get_contents($url); $data = str_getcsv($csv); var_dump($data);
最后和第一个元素连接在一个string中:
[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 ) )
我希望这可以有一些帮助。
方便的手册:
$csv = array_map('str_getcsv', file('data.csv'));
我用下面的函数将csvstringparsing为关联数组
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; }
如果你的csv文件名是mycsv.csv,那么你可以调用这个函数:
$dataArray = csvToArray(mycsv.csv);
你应该使用fgetcsv。 由于csv是一个variables,因此不能将文件导入为stream,那么应该首先使用php://temp
或php://memory
将string伪装为文件:
$fp = fopen("php://temp", 'r+'); fputs($fp, $csvText); rewind($fp);
那么你将没有问题使用fgetcsv:
$csv = []; while ( ($data = fgetcsv($fp) ) !== FALSE ) { $csv[] = $data; }
$data
将是一个单一的csv行的数组(可能包括换行符或逗号等),因为它应该是。
略短的版本,没有不必要的第二个variables:
$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); }
如果您需要csv列的名称,则可以使用此方法
$example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));