{"id":458,"date":"2019-02-27T12:11:33","date_gmt":"2019-02-27T11:11:33","guid":{"rendered":"https:\/\/bastienmalahieude.fr\/?p=458"},"modified":"2019-03-02T11:02:49","modified_gmt":"2019-03-02T10:02:49","slug":"exporter-tableau-php-csv-excel","status":"publish","type":"post","link":"https:\/\/bastienmalahieude.fr\/en\/export-array-php-csv-microsoft-excel\/","title":{"rendered":"Export a PHP array to CSV, compatible with UTF-8 and Microsoft Excel"},"content":{"rendered":"

In this first article of the series, we will try to create a function to export a PHP array as a CSV file, readable in Excel.<\/p>\n

The purpose of the manipulation is to have in input data a\u00a0PHP\u00a0associative array<\/a>\u00a0and output a CSV file that will be downloaded to the user’s computer.\u00a0For that, we will create the\u00a0export_data_to_csv<\/em>\u00a0() function.<\/p>\n

We will try to export the following PHP array<\/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

Into a CSV file that will contain all these 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

Our function will take 4 arguments to make it as flexible as possible<\/p>\n