PHP CSV string to array

PhpParsingCsv

Php Problem Overview


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

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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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:

$fp = fopen("php://temp", 'r+');
fputs($fp, $csvText);
rewind($fp);

Then you will have no problem using fgetcsv:

$csv = [];
while ( ($data = fgetcsv($fp) ) !== FALSE ) {
	$csv[] = $data;
}
fclose($fp)

$data will be an array of a single csv line (which may include line breaks or commas, etc), as it should be.

Caveat: The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes. (the default is 2 MB) http://www.php.net/manual/en/wrappers.php.php

Solution 3 - Php

Handy oneliner:

$csv = array_map('str_getcsv', file('data.csv'));

Solution 4 - Php

I have used following function to parse csv string to associative array

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:

$dataArray = csvToArray(mycsv.csv);

you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/

Solution 5 - Php

A modification of previous answers using array_map.
Blow up the CSV data with multiple lines.

$csv = array_map('str_getcsv', explode("\n", $csvData));

Solution 6 - Php

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

Solution 7 - Php

If you need a name for the csv columns, you can use this method

 $example= array_map(function($v) {$column = str_getcsv($v, ";");return array("foo" => $column[0],"bar" => $column[1]);},file('file.csv'));

Solution 8 - Php

If you have carriage return/line feeds within columns, str_getcsv will not work.

Try 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
}

Solution 9 - Php

You can convert CSV string to Array with this function.

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

Solution 10 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomzieView Question on Stackoverflow
Solution 1 - Phpsaran banerjeeView Answer on Stackoverflow
Solution 2 - PhpiateadonutView Answer on Stackoverflow
Solution 3 - PhpGauiView Answer on Stackoverflow
Solution 4 - PhpRajen K BhagatView Answer on Stackoverflow
Solution 5 - PhpJoseph D.View Answer on Stackoverflow
Solution 6 - PhpuserView Answer on Stackoverflow
Solution 7 - PhpRamsés FernándezView Answer on Stackoverflow
Solution 8 - PhpStacey RichardsView Answer on Stackoverflow
Solution 9 - PhpAlper AKPINARView Answer on Stackoverflow
Solution 10 - PhpAhmad Al- HashlamounView Answer on Stackoverflow