{"id":481,"date":"2019-03-14T11:00:13","date_gmt":"2019-03-14T10:00:13","guid":{"rendered":"https:\/\/bastienmalahieude.fr\/?p=481"},"modified":"2019-03-02T11:48:41","modified_gmt":"2019-03-02T10:48:41","slug":"importer-un-fichier-csv-en-tableau-php","status":"publish","type":"post","link":"https:\/\/bastienmalahieude.fr\/en\/importer-un-fichier-csv-en-tableau-php\/","title":{"rendered":"Import a CSV file into a PHP array"},"content":{"rendered":"

In a first article we saw how to\u00a0transform a PHP array and export it to a CSV file<\/a>\u00a0.\u00a0This article is the opposite, it will allow you to generate a PHP array from a CSV file.<\/p>\n

We will transform a CSV file containing this kind of data:<\/p>\n \n \n \n \n \n \n
first name<\/th>\n last name<\/th>\n phone<\/th>\n email<\/th>\n <\/tr>\n <\/thead>\n
Bastien<\/td>\n Malahieude<\/td>\n 06 XX XX XX XX XX<\/td>\n contact@bastienmalahieude.fr<\/td>\n <\/tr>\n
John<\/td>\n Doe<\/td>\n 06 XX XX XX XX XX<\/td>\n john@doe.fr<\/td>\n <\/tr>\n <\/tbody>\n <\/table>\n\n\n \n

 <\/p>\n

and return a PHP array like this one:<\/p>\n

array(2) {\n  [0]=>\n  array(4) {\n    [\"first name\"]=>\n    string(7) \"Bastien\"\n    [\"last name\"]=>\n    string(10) \"Malahieude\"\n    [\"phone\"]=>\n    string(17) \"06 XX XX XX XX XX\"\n    [\"email\"]=>\n    string(28) \"contact@bastienmalahieude.fr\"\n  }\n  [1]=>\n  array(4) {\n    [\"first name\"]=>\n    string(4) \"John\"\n    [\"last name\"]=>\n    string(3) \"Doe\"\n    [\"phone\"]=>\n    string(17) \"06 XX XX XX XX XX\"\n    [\"email\"]=>\n    string(11) \"john@doe.fr\"\n  }\n}\n<\/pre>\n

 <\/p>\n

For that we will create an\u00a0import_csv_to_array<\/em>\u00a0function\u00a0which reads the data from a file and returns a PHP array. This function takes two parameters, but only one is mandatory:<\/p>\n