Sick Gaming
[Tut] Convert PHP Array to CSV - Printable Version

+- Sick Gaming (
+-- Forum: Programming (
+--- Forum: PHP Development (
+--- Thread: [Tut] Convert PHP Array to CSV (/thread-100635.html)

[Tut] Convert PHP Array to CSV - xSicKxBot - 01-24-2023

Convert PHP Array to CSV

<div style="margin: 5px 5% 10px 5%;"><img src="" width="550" height="289" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="">Vincy</a>. Last modified on January 23rd, 2023.</div>
<p>This tutorial is to convert a PHP array to a CSV file or format. It has two examples of implementing this conversion.</p>
<li>A quick example is that parses a PHP array dataset to a CSV and prints the CSV data on the browser.</li>
<li>Another example is to convert the database array to CSV and download the .csv file.</li>
<h2>Example 1: Quick example</h2>
<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>
<li>A target CSV file.</li>
<li>Iterating array pinter to put the CSV row.</li>
<li>Data delimiter.</li>
<li>Data enclosure.</li>
<div class="post-section-highlight" readability="52">
<pre class="prettyprint"><code class="lang-php">&lt;?php
$array = array( array(100, 200, 300, 400, 500), array('Lion', 'Tiger', 'Elephant', 'Horse', 'Dog "Domestic"'),
$csvDelimiter = ',';
$csvEnclosure = '"'; // to physically write to a file in disk
$csvFile = fopen('example.csv', 'w+'); // to write to temp
$csvFile = fopen('php://temp', 'r+'); foreach ($array as $line) { fputcsv($csvFile, $line, $csvDelimiter, $csvEnclosure);
rewind($csvFile); // to display CSV file contents on browser
$contents = '';
while (!feof($csvFile)) { $contents .= fread($csvFile, 8192);
echo $contents;
<p><img loading="lazy" class="alignnone size-large wp-image-20189" src="" alt="php array to csv" width="550" height="289" srcset=" 550w, 300w, 768w, 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<p>This quick example creates an input array for converting into CSV. This is a multidimensional array that has the dataset.</p>
<p>This code sets the delimiter and enclosure before converting the input array.</p>
<p>It iterates the array and calls <em>fputcsv()</em> on each iteration to form the data row.</p>
<p>Get the code from the linked article if you want to <a href="">convert CSV to a PHP array</a>.</p>
<h2>Example 2: Convert database result array to CSV to download</h2>
<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="">handle CSV in PHP to read, write, import, and export operations with a database</a>.</p>
<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>
<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>
<p>The PHP header() is set with the <em>application/csv</em> to download the CSV file to the browser.</p>
<pre class="prettyprint"><code class="lang-php">&lt;?php
// PHP code will connect to a database
// Read from a table and get result
// Formulate the result as an array to use in a convenient form
// Iterate the array
// Use PHP's function fputcsv and write the array elements
// to a CSV file
// Then push that CSV file as download
$mysqli = new mysqli("localhost", "root", "", "db_phppot_examples");
$i = 0;
$query = "SELECT id, name, type FROM tbl_php_array_to_csv";
if ($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++; }
$fileOut = fopen("php://output", 'w') or die("Unable open php://output"); // Header forces the CSV file to download
// writing the first CSV record as the column labels
// Refer:
fputcsv($fileOut, array('id', 'name', 'type')); // writing array elements as CSV file records one by one
foreach ($animalArray as $animal) { fputcsv($fileOut, $animal);
fclose($fileOut) or die("Unable to close php://output");
<h3>Database script</h3>
<p>This database script imports the table structure and data to run this example.</p>
<p>You may also try this code with a different database table. It requires only minor code changes to edit the new table’s column names.</p>
<pre class="prettyprint"><code class="language-sql">--
-- Database: `db_phppot_examples`
-- -- -------------------------------------------------------- --
-- Table structure for table `tbl_php_array_to_csv`
-- CREATE TABLE `tbl_php_array_to_csv` ( `id` int NOT NULL, `name` varchar(255) NOT NULL, `type` varchar(255) NOT NULL
); --
-- Dumping data for table `tbl_php_array_to_csv`
-- INSERT INTO `tbl_php_array_to_csv` (`id`, `name`, `type`) VALUES
(1, 'Lion', 'Wild'),
(3, 'Dog', 'Domestic'),
(4, 'Tiger', 'Wild'); --
-- Indexes for dumped tables
-- --
-- Indexes for table `tbl_php_array_to_csv`
ALTER TABLE `tbl_php_array_to_csv` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `tbl_php_array_to_csv`
<h2>Uses of PHP array to CSV conversion</h2>
<h3>(1) Database table export</h3>
<p>We can use this code export database to a CSV file. It is for taking a backup of a database table.</p>
<p>If you want to create a PHP program to <a href="">take a complete database backup into an excel</a>, the linked article has the code.</p>
<h3>(2) Format data into a comma-separated value</h3>
<p>It helps to convert various data sources and create a dumb in a unified CSV format.</p>
<p>In case of loading more data from an array into an existing CSV, this code will be helpful.</p>
<p><a class="download" href="">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
<p> <a href="" class="top">↑ Back to Top</a> </p>