{"id":131381,"date":"2023-01-23T13:02:47","date_gmt":"2023-01-23T13:02:47","guid":{"rendered":"https:\/\/phppot.com\/?p=20175"},"modified":"2023-01-23T13:02:47","modified_gmt":"2023-01-23T13:02:47","slug":"convert-php-array-to-csv","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/01\/23\/convert-php-array-to-csv\/","title":{"rendered":"Convert PHP Array to CSV"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1304347826087\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on January 23rd, 2023.<\/div>\n<p>This tutorial is to convert a PHP array to a CSV file or format. It has two examples of implementing this conversion.<\/p>\n<ol>\n<li>A quick example is that parses a PHP array dataset to a CSV and prints the CSV data on the browser.<\/li>\n<li>Another example is to convert the database array to CSV and download the .csv file.<\/li>\n<\/ol>\n<h2>Example 1: Quick example<\/h2>\n<p>The below code uses the PHP <em>fputcsv()<\/em> function to convert the array to CSV. This function requires the following arguments to specify.<\/p>\n<ol>\n<li>A target CSV file.<\/li>\n<li>Iterating array pinter to put the CSV row.<\/li>\n<li>Data delimiter.<\/li>\n<li>Data enclosure.<\/li>\n<\/ol>\n<div class=\"post-section-highlight\" readability=\"52\">\n<pre class=\"prettyprint\"><code class=\"lang-php\">&lt;?php\n$array = array( array(100, 200, 300, 400, 500), array('Lion', 'Tiger', 'Elephant', 'Horse', 'Dog \"Domestic\"'),\n);\n$csvDelimiter = ',';\n$csvEnclosure = '\"'; \/\/ to physically write to a file in disk\n$csvFile = fopen('example.csv', 'w+'); \/\/ to write to temp\n$csvFile = fopen('php:\/\/temp', 'r+'); foreach ($array as $line) { fputcsv($csvFile, $line, $csvDelimiter, $csvEnclosure);\n}\nrewind($csvFile); \/\/ to display CSV file contents on browser\n$contents = '';\nwhile (!feof($csvFile)) { $contents .= fread($csvFile, 8192);\n}\nfclose($csvFile);\necho $contents;\n?&gt;\n<\/code><\/pre>\n<\/div>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-20189\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-array-to-csv-550x289.jpg\" alt=\"php array to csv\" width=\"550\" height=\"289\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-array-to-csv-550x289.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-array-to-csv-300x158.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-array-to-csv-768x403.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-array-to-csv.jpg 1200w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<p>This quick example creates an input array for converting into CSV. This is a multidimensional array that has the dataset.<\/p>\n<p>This code sets the delimiter and enclosure before converting the input array.<\/p>\n<p>It iterates the array and calls <em>fputcsv()<\/em> on each iteration to form the data row.<\/p>\n<p>Get the code from the linked article if you want to <a href=\"https:\/\/phppot.com\/php\/php-csv-to-array\/\">convert CSV to a PHP array<\/a>.<\/p>\n<h2>Example 2: Convert database result array to CSV to download<\/h2>\n<p>This PHP code is to learn how to convert an array of data from the database to CSV. Previously, we have seen how to <a href=\"https:\/\/phppot.com\/php\/how-to-handle-csv-with-php-read-write-import-export-with-database\/\">handle CSV in PHP to read, write, import, and export operations with a database<\/a>.<\/p>\n<p>In this example, code connects the database and reads the results into an array. Then, it creates a PHP file output stream to put the CSV data row by row.<\/p>\n<p>First, the code sets the array of column headers. Then, it iterates the database result array and calls <em>fputcsv()<\/em> on each row of data.<\/p>\n<p>The PHP header() is set with the <em>application\/csv<\/em> to download the CSV file to the browser.<\/p>\n<pre class=\"prettyprint\"><code class=\"lang-php\">&lt;?php\n\/\/ PHP code will connect to a database\n\/\/ Read from a table and get result\n\/\/ Formulate the result as an array to use in a convenient form\n\/\/ Iterate the array\n\/\/ Use PHP's function fputcsv and write the array elements\n\/\/ to a CSV file\n\/\/ Then push that CSV file as download\n$mysqli = new mysqli(\"localhost\", \"root\", \"\", \"db_phppot_examples\");\n$i = 0;\n$query = \"SELECT id, name, type FROM tbl_php_array_to_csv\";\nif ($resultArray = $mysqli-&gt;query($query)) { while ($record = $resultArray-&gt;fetch_array()) { $animalArray[$i]['id'] = $record['id']; $animalArray[$i]['name'] = $record['name']; $animalArray[$i]['type'] = $record['type']; $i++; }\n}\n$fileOut = fopen(\"php:\/\/output\", 'w') or die(\"Unable open php:\/\/output\"); \/\/ Header forces the CSV file to download\nheader(\"Content-Type:application\/csv\");\nheader(\"Content-Disposition:attachment;filename=example-csv.csv\");\n\/\/ writing the first CSV record as the column labels\n\/\/ Refer: https:\/\/www.php.net\/manual\/en\/function.fputcsv.php\nfputcsv($fileOut, array('id', 'name', 'type')); \/\/ writing array elements as CSV file records one by one\nforeach ($animalArray as $animal) { fputcsv($fileOut, $animal);\n}\nfclose($fileOut) or die(\"Unable to close php:\/\/output\");\n?&gt;\n<\/code><\/pre>\n<h3>Database script<\/h3>\n<p>This database script imports the table structure and data to run this example.<\/p>\n<p>You may also try this code with a different database table. It requires only minor code changes to edit the new table\u2019s column names.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-sql\">--\n-- Database: `db_phppot_examples`\n-- -- -------------------------------------------------------- --\n-- Table structure for table `tbl_php_array_to_csv`\n-- CREATE TABLE `tbl_php_array_to_csv` ( `id` int NOT NULL, `name` varchar(255) NOT NULL, `type` varchar(255) NOT NULL\n); --\n-- Dumping data for table `tbl_php_array_to_csv`\n-- INSERT INTO `tbl_php_array_to_csv` (`id`, `name`, `type`) VALUES\n(1, 'Lion', 'Wild'),\n(3, 'Dog', 'Domestic'),\n(4, 'Tiger', 'Wild'); --\n-- Indexes for dumped tables\n-- --\n-- Indexes for table `tbl_php_array_to_csv`\n--\nALTER TABLE `tbl_php_array_to_csv` ADD PRIMARY KEY (`id`); --\n-- AUTO_INCREMENT for dumped tables\n-- --\n-- AUTO_INCREMENT for table `tbl_php_array_to_csv`\n--\nALTER TABLE `tbl_php_array_to_csv` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;\n<\/code><\/pre>\n<h2>Uses of PHP array to CSV conversion<\/h2>\n<h3>(1) Database table export<\/h3>\n<p>We can use this code export database to a CSV file. It is for taking a backup of a database table.<\/p>\n<p>If you want to create a PHP program to <a href=\"https:\/\/phppot.com\/php\/database-data-export-to-excel-file-using-php\/\">take a complete database backup into an excel<\/a>, the linked article has the code.<\/p>\n<h3>(2) Format data into a comma-separated value<\/h3>\n<p>It helps to convert various data sources and create a dumb in a unified CSV format.<\/p>\n<p>In case of loading more data from an array into an existing CSV, this code will be helpful.<\/p>\n<p><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/php-array-to-csv.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-array-to-csv\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on January 23rd, 2023. This tutorial is to convert a PHP array to a CSV file or format. It has two examples of implementing this conversion. A quick example is that parses a PHP array dataset to a CSV and prints the CSV data on the browser. Another example is to [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":131382,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-131381","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/131381","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=131381"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/131381\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/131382"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=131381"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=131381"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=131381"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}