php create csv from array
Convert php array to csv string
I have several method to transform php array to csv string both from stackoverflow and google. But I am in trouble that if I want to store mobile number such as 01727499452, it saves as without first 0 value. I am currently using this piece of code: Convert array into csv
Can anyone please help me.
9 Answers 9
You could use str_putcsv function:
More about this on GitHub, a function created by @johanmeiring.
This is what you need
It runs through your array creating a new line on each loop seperating the array values with a «,».
Inspired by @alexcristea’s answer:
Are you sure the numbers are actually being saved without the leading zero? Have you looked at the actual CSV output in a text editor?
If you’ve just opened up the CSV file in a spreadsheet application, it is most likely the spreadsheet that is interpreting your telephone numbers as numeric values and dropping the zeros when displaying them. You can usually fix that in the spreadsheet by changing the formatting options on that particular column.
Since it’s a CSV and not something like JSON, everything is going to be read as a string anyway so just convert your number to a string with:
PHP’s gettype() would also be an option. You can type cast every field to a string (even if it already is one) by using one of the methods I described or you can call out just the number field you’re after by doing this:
Here’s the full code with it added
PHP Array to CSV
I’m trying to convert an array of products into a CSV file, but it doesn’t seem to be going to plan. The CSV file is one long line, here is my code:
If anyone else was looking for the same thing, found a better way of doing it:
7 Answers 7
This may solve your problem immediately.
Note from comment: I should mention that this will be making a file on your server, so you’ll need to read that file’s contents before outputting it, also if you don’t want to save a copy then you’ll need to ùnlink`the file when you are done
This is a simple solution that exports an array to csv string:
To terminate each new line in your CSV output.
I’m assuming that the text is delimiting, but isn’t moving to the next row?
That’s a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses «\r\n». I wracked my brains with that one when my output wasn’t breaking to a new line.
In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:
Since the various levels of my array didn’t lend themselves well to a the flat CSV format, I created a blank column with the sub-array’s key to serve as a descriptive «intro» to the next level of data. Sample output:
You could easily remove that «intro» (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:
after the is_array() to compact the code further and remove the extra column.
Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:
Yes, I know I leave an extra comma, but for the sake of brevity, I didn’t handle it here.
fputcsv
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
fputcsv — Форматирует строку в виде CSV и записывает её в файловый указатель
Описание
Список параметров
Указатель на файл должен быть корректным и указывать на файл, успешно открытый функциями fopen() или fsockopen() (и всё ещё не закрытый функцией fclose() ).
Массив строк ( string ).
Дополнительный параметр separator устанавливает разделитель полей (только один однобайтовый символ).
Дополнительный параметр enclosure устанавливает ограничитель полей (только один однобайтовый символ).
Необязательный параметр escape_char задаёт экранирующий символ (не более одного однобайтового символа). Пустая строка ( «» ) отключает проприетарный механизм экранирования.
Возвращаемые значения
Возвращает длину записанной строки или false в случае возникновения ошибки.
Список изменений
Версия | Описание |
---|---|
7.4.0 | Теперь параметр escape_char может принимать пустую строку для отключения проприетарного механизма экранирования. |
Примеры
Пример #1 Пример использования fputcsv()
Вышеуказанный пример запишет в файл file.csv следующее:
Примечания
Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.
Смотрите также
User Contributed Notes 26 notes
If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..
If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it’s contents:
Sometimes it’s useful to get CSV line as string. I.e. to store it somewhere, not in on a filesystem.
if you want make UTF-8 file for excel, use this:
Please note, that fputcsv ist not always enclosing strings with the enclosure character.
It seems that only strings containing at least one of the following characters are enclosed:
— the delimiter character
— the enclosure character
— the escape character
— \n (new line)
— \r (line feed)
— \t (tab)
— blank
I hope this saves you the hour it took me to get to the bottom of this behaviour.
Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function. The ascii code for tab is 9, so chr(9) returns a tab character.
Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.
the solution for how to solve the encoding problem while converting an array to csv file is below.
Alright, after playing a while, I’m confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.
INTO TABLE
my_table
FIELDS TERMINATED BY
‘,’
OPTIONALLY ENCLOSED BY
‘»‘
LINES TERMINATED BY
‘\n’
*/
I’ve created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I’m looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626
This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn’t occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)
I converted this from the PHP source code. This replicates PHP5 functionality exactly, whereas the other examples here do not.
if (! function_exists ( ‘fputcsv’ )) <
To produce RFC 4180 conforming output, do not use fputcsv but encode manually, like this:
Convert array into csv
How to convert an array into a CSV file?
7 Answers 7
I’m using the following function for that; it’s an adaptation from one of the man entries in the fputscsv comments. And you’ll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.
My solution requires the array be formatted differently than provided in the question:
We define our function:
Then we output our data as a CSV:
I have used this with several projects, and it works well. I should note that the outputCSV code is more clever than I am, so I am sure I am not the original author. Unfortunately I have lost track of where I got it, so I can’t give the credit to whom it is due.
Credit to Kingjeffrey above and also to this blog post where I found the information about creating text streams.
The accepted answer from Paul is great. I’ve made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):
So I just took Paul’s function from above:
So you can just call:
If you want a special line ending you can use the optional parameter «glue» for this.
Add some improvements based on accepted answer.
Well maybe a little late after 4 years haha. but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV.
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
The end result is that you get something like this:
How to create and download a csv file from php script?
I am a novice programmer and I searched a lot about my question but couldn’t find a helpful solution or tutorial about this.
My goal is I have a PHP array and the array elements are showing in a list on the page.
I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.
I don’t know how to do this. I have searched a lot too. But yet to find any helpful resource.
Please provide me some tutorial or solution or advice to implement it by myself. As I’m a novice please provide easy to implement solutions.
My array looks like:
6 Answers 6
You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:
To make the browsers offer the «Save as» dialog, you will have to send HTTP headers like this (see more about this header in the rfc):
Putting it all together:
And you can use it like this:
Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:
I don’t have enough reputation to reply to @complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of «export.csv» the file gets saved as «export.csv—«). Probably it tries to sanitize \r\n at the end of the header line.
Correct line should look like this:
In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:
Also, I find it more elegant to use rewind() instead of fseek():