Php file_get_contents csv to array
I'm trying to parse a CSV string to an array in PHP. The CSV string has the following attributes:
Example content:
When I try to parse it like this:
The last and first element are concatenated in one string:
How can I fix this? Any help would be appreciated.
user 20.8k9 gold badges109 silver badges98 bronze badges asked Jul 20, 2013 at 10:18
2 Do this:
It will give you an output like this:
I hope this can be of some help. answered Jul 20, 2013 at 10:44
saran banerjeesaran banerjee 2,8251 gold badge12 silver badges12 bronze badges 11 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
Then you will have no problem using fgetcsv:
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 answered Jun 9, 2017 at 3:43
iateadonutiateadonut 1,66416 silver badges27 bronze badges 7 Handy oneliner:
answered Dec 10, 2014 at 20:44
GauiGaui 8,46315 gold badges63 silver badges88 bronze badges 8 I have used following function to parse csv string to associative array
if your csv file name is mycsv.csv then you call this function as:
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/ answered Sep 22, 2014 at 15:27
1 A modification of previous
answers using
answered May 11, 2018 at 23:08
Joseph D.Joseph D. 11.2k3 gold badges29 silver badges62 bronze badges Slightly shorter version, without unnecessary second variable:
answered Dec 1, 2014 at 19:53
useruser 20.8k9 gold badges109 silver badges98 bronze badges 1 If you need a name for the csv columns, you can use this method
answered Sep 24, 2017 at 10:41
If you have carriage return/line feeds within columns, str_getcsv will not work. Try https://github.com/synappnz/php-csv Use:
answered Oct 4, 2018 at 10:20
Stacey RichardsStacey Richards 6,4267 gold badges37 silver badges40 bronze badges You can convert CSV string to Array with this function.
answered Apr 7, 2020 at 10:15
Try this, it's working for me:
answered Apr 9, 2020 at 14:54
1 |