Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CSV string to array

Tags:

php

parsing

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: \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.

like image 437
Tomzie Avatar asked Jul 20 '13 10:07

Tomzie


People also ask

How to convert string with comma to array PHP?

Given a long string separated with comma delimiter. The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter.

How to split a string into an array PHP?

PHP explode() is a built-in function that splits the string by the specified string into array elements. The explode() function takes three arguments and returns an array containing string elements. The explode() function breaks the string into an array.

How do I convert a CSV file to an array?

Converting the Raw CSV File Into an Array We can use the fgetcsv() function to automatically convert the contents of the CSV file into an array, or we can use array_map .

How do I read a csv file in column wise in PHP?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==


1 Answers

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.

like image 101
saran banerjee Avatar answered Sep 23 '22 12:09

saran banerjee