Create an account


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

#1
Convert PHP JSON to CSV

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/03/convert-php-json-to-csv.jpg" width="550" height="413" title="" alt="" /></div><div><div class="modified-on" readability="7.0697674418605"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on March 7th, 2023.</div>
<p>This tutorial gives examples for converting a PHP JSON variable content into a CSV file.</p>
<p>This quick example achieves it in a few steps. It uses the PHP fputcsv() method to prepare the CSV output.</p>
<ol>
<li>It reads the input JSON and decodes it into an array.</li>
<li>Iterate the JSON array to read the line of the record.</li>
<li>Apply PHP fputcsv() to write the array keys in the header, followed by array values.</li>
</ol>
<h2>Quick example</h2>
<div class="post-section-highlight" readability="41">
<pre class="prettyprint"><code class="language-php">&lt;?php function convertJsonToCSV($jsonFile, $csvFile)
{ if (($json = file_get_contents($jsonFile)) == false) { die('Unable to read JSON file.'); } $jsonString = json_decode($json, true); $fp = fopen($csvFile, 'w'); fputcsv($fp, array_keys($jsonString[0])); for ($i = 0; $i &lt; count($jsonString); $i ++) { fputcsv($fp, array_values($jsonString[$i])); } fclose($fp); return;
}
$jsonFile = 'animals.json';
$csvFile = 'animals.csv'; convertJsonToCSV($jsonFile, $csvFile);
echo 'JSON to CSV converted. &lt;a href="' . $csvFile . '" target="_blank"&gt;Download CSV file&lt;/a&gt;';
</code></pre>
</div>
<p>The input JSON file is in the local drive and specified to a PHP variable $jsonFile.</p>
<p>This example creates a custom function convertJsonToCSV(). It requires the input JSON and the target CSV file names.</p>
<p>It converts the input JSON object to a PHP array. Then, it iterates the <a href="https://phppot.com/php/power-of-php-arrays/">PHP array</a> to read the row.</p>
<p>This function uses the PHP fputcsv() function to write each row into the target CSV file.</p>
<p><strong>Output:</strong></p>
<p>The above program will return the following CSV content in a file. In a previous tutorial, we have seen <a href="https://phppot.com/php/php-csv-file-export-using-fputcsv/">how to export to a CSV file using the PHP fputcsv() function</a>.</p>
<pre class="prettyprint"><code>Id,Name,Type,Role
1,Lion,Wild,"Lazy Boss"
2,Tiger,Wild,CEO
3,Jaguar,Wild,Developer
</code></pre>
<p>Note: The input JSON must be a one-dimensional associative array to get a better output.</p>
<p><img loading="lazy" class="alignnone size-large wp-image-20354" src="https://phppot.com/wp-content/uploads/2023/01/php-json-to-csv-550x413.jpg" alt="php json to csv" width="550" height="413" srcset="https://phppot.com/wp-content/uploads/2023/01/php-json-to-csv-550x413.jpg 550w, https://phppot.com/wp-content/uploads/20...00x225.jpg 300w, https://phppot.com/wp-content/uploads/20...68x576.jpg 768w, https://phppot.com/wp-content/uploads/20...to-csv.jpg 960w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>JSON string to CSV in PHP</h2>
<p>This example has a different approach to dealing with PHP JSON to CSV conversion.</p>
<p>It uses a JSON string as its input instead of reading a file. The JSON string input is initiated in a PHP variable and passed to the&nbsp;<em>convertJSONtoCSV()</em> function.</p>
<p>It reads the JSON string and converts it into a JSON array to prepare CSV. The linked article has an example of <a href="https://phppot.com/php/php-csv-file-read/">reading CSV using PHP</a>.</p>
<p>Then, it iterates the JSON array and applies PHP fputcsv() to write the CSV row.</p>
<p>It reads the array_keys to supply the CSV header. And this will be executed only for the first time. It writes the column names as the first row of the output CSV.</p>
<p class="code-heading">json-string-to-csv.php</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
function convertJsonToCSV($jsonString, $csvFile)
{ $jsonArray = json_decode($jsonString, true); $fp = fopen($csvFile, 'w'); $header = false; foreach ($jsonArray as $line) { if (empty($header)) { $header = array_keys($line); fputcsv($fp, $header); $header = array_flip($header); } fputcsv($fp, array_merge($header, $line)); } fclose($fp); return;
}
$jsonString = '[ { "Id": "1", "Name": "Lion", "Type": "Wild", "Role": "Lazy Boss" }, { "Id": "2", "Name": "Tiger", "Type": "Wild", "Role": "CEO" }, { "Id": "3", "Name": "Jaguar", "Type": "Wild", "Role": "Developer" }
]';
$csvFile = 'animals.csv'; convertJsonToCSV($jsonString, $csvFile);
echo 'JSON to CSV converted. &lt;a href="' . $csvFile . '" target="_blank"&gt;Download CSV file&lt;/a&gt;';
</code></pre>
<h2>Upload CSV file to convert into JSON in PHP</h2>
<p>This example is to perform the JSON to CSV with a file upload option.</p>
<p>This code will be helpful if you want to convert the uploaded JSON file into a CSV.</p>
<p>It shows an HTML form with a file input field. This field will accept only ‘.json’ files. The restriction is managed with the HTML ‘accept’ attribute. It can also be validated with a <a href="https://phppot.com/php/php-image-upload-with-size-type-dimension-validation/">server-side file validation script in PHP</a>.</p>
<p>The $_FILES[‘csv-file’][‘tmp_name’] contains the posted CSV file content. The JSON to CSV conversion script uses the uploaded file content.</p>
<p>Then, it parses the JSON and converts it into CSV. Once converted, the link will be shown to the browser to download the file.</p>
<p class="code-heading">upload-json-to-convert-to-csv.php</p>
<pre class="prettyprint"><code class="language-php-template">&lt;?php
if (! empty($_FILES["csv-file"]["tmp_name"])) { $csvFile = 'animal.csv'; if (($json = file_get_contents($_FILES["csv-file"]["tmp_name"])) == false) { die('Unable to read JSON file.'); } $jsonString = json_decode($json, true); $fp = fopen($csvFile, 'w'); fputcsv($fp, array_keys($jsonString[0])); for ($i = 0; $i &lt; count($jsonString); $i ++) { fputcsv($fp, array_values($jsonString[$i])); } fclose($fp); echo 'JSON to CSV converted. &lt;a href="' . $csvFile . '" target="_blank"&gt;Download CSV file&lt;/a&gt;';
}
?&gt;
&lt;HTML&gt;
&lt;head&gt;
&lt;title&gt;Convert JSON to CSV&lt;/title&gt;
&lt;style&gt;
body { font-family: arial;
} input[type="file"] { padding: 5px 10px; margin: 30px 0px; border: #666 1px solid; border-radius: 3px;
}
input[type="submit"] { padding: 8px 20px; border: #232323 1px solid; border-radius: 3px; background: #232323; color: #FFF;
}
&lt;/style&gt;
&lt;/head&gt; &lt;body&gt; &lt;form method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="csv-file" accept=".json" /&gt; &lt;input type="submit" name="upload" value="Upload"&gt; &lt;/form&gt;
&lt;/body&gt;
&lt;/HTML&gt;
</code></pre>
<p><a class="download" href="https://phppot.com/downloads/php/php-json-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/convert-php-json-to-csv/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2023/03/...on-to-csv/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016