Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Convert PHP Array to CSV

#1
Convert PHP Array to CSV

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/01/convert-php-array-to-csv.jpg" width="550" height="289" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">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>
<ol>
<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>
</ol>
<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>
<ol>
<li>A target CSV file.</li>
<li>Iterating array pinter to put the CSV row.</li>
<li>Data delimiter.</li>
<li>Data enclosure.</li>
</ol>
<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);
}
fclose($csvFile);
echo $contents;
?&gt;
</code></pre>
</div>
<p><img 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/20...00x158.jpg 300w, https://phppot.com/wp-content/uploads/20...68x403.jpg 768w, https://phppot.com/wp-content/uploads/20...to-csv.jpg 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="https://phppot.com/php/php-csv-to-array/">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="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>
<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
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=example-csv.csv");
// writing the first CSV record as the column labels
// Refer: https://www.php.net/manual/en/function.fputcsv.php
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");
?&gt;
</code></pre>
<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`
--
ALTER TABLE `tbl_php_array_to_csv` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
</code></pre>
<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="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>
<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="https://phppot.com/downloads/php/php-array-to-csv.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-array-to-csv/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2023/01/...ay-to-csv/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016