{"id":132287,"date":"2023-03-07T05:06:52","date_gmt":"2023-03-07T05:06:52","guid":{"rendered":"https:\/\/phppot.com\/?p=20285"},"modified":"2023-03-07T05:06:52","modified_gmt":"2023-03-07T05:06:52","slug":"convert-php-json-to-csv","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/03\/07\/convert-php-json-to-csv\/","title":{"rendered":"Convert PHP JSON to CSV"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.0697674418605\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on March 7th, 2023.<\/div>\n<p>This tutorial gives examples for converting a PHP JSON variable content into a CSV file.<\/p>\n<p>This quick example achieves it in a few steps. It uses the PHP fputcsv() method to prepare the CSV output.<\/p>\n<ol>\n<li>It reads the input JSON and decodes it into an array.<\/li>\n<li>Iterate the JSON array to read the line of the record.<\/li>\n<li>Apply PHP fputcsv() to write the array keys in the header, followed by array values.<\/li>\n<\/ol>\n<h2>Quick example<\/h2>\n<div class=\"post-section-highlight\" readability=\"41\">\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php function convertJsonToCSV($jsonFile, $csvFile)\n{ 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;\n}\n$jsonFile = 'animals.json';\n$csvFile = 'animals.csv'; convertJsonToCSV($jsonFile, $csvFile);\necho 'JSON to CSV converted. &lt;a href=\"' . $csvFile . '\" target=\"_blank\"&gt;Download CSV file&lt;\/a&gt;';\n<\/code><\/pre>\n<\/div>\n<p>The input JSON file is in the local drive and specified to a PHP variable $jsonFile.<\/p>\n<p>This example creates a custom function convertJsonToCSV(). It requires the input JSON and the target CSV file names.<\/p>\n<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>\n<p>This function uses the PHP fputcsv() function to write each row into the target CSV file.<\/p>\n<p><strong>Output:<\/strong><\/p>\n<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>\n<pre class=\"prettyprint\"><code>Id,Name,Type,Role\n1,Lion,Wild,\"Lazy Boss\"\n2,Tiger,Wild,CEO\n3,Jaguar,Wild,Developer\n<\/code><\/pre>\n<p>Note: The input JSON must be a one-dimensional associative array to get a better output.<\/p>\n<p><img decoding=\"async\" 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\/2023\/01\/php-json-to-csv-300x225.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-json-to-csv-768x576.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/01\/php-json-to-csv.jpg 960w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>JSON string to CSV in PHP<\/h2>\n<p>This example has a different approach to dealing with PHP JSON to CSV conversion.<\/p>\n<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>\n<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>\n<p>Then, it iterates the JSON array and applies PHP fputcsv() to write the CSV row.<\/p>\n<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>\n<p class=\"code-heading\">json-string-to-csv.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\nfunction convertJsonToCSV($jsonString, $csvFile)\n{ $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;\n}\n$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\" }\n]';\n$csvFile = 'animals.csv'; convertJsonToCSV($jsonString, $csvFile);\necho 'JSON to CSV converted. &lt;a href=\"' . $csvFile . '\" target=\"_blank\"&gt;Download CSV file&lt;\/a&gt;';\n<\/code><\/pre>\n<h2>Upload CSV file to convert into JSON in PHP<\/h2>\n<p>This example is to perform the JSON to CSV with a file upload option.<\/p>\n<p>This code will be helpful if you want to convert the uploaded JSON file into a CSV.<\/p>\n<p>It shows an HTML form with a file input field. This field will accept only \u2018.json\u2019 files. The restriction is managed with the HTML \u2018accept\u2019 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>\n<p>The $_FILES[\u2018csv-file\u2019][\u2018tmp_name\u2019] contains the posted CSV file content. The JSON to CSV conversion script uses the uploaded file content.<\/p>\n<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>\n<p class=\"code-heading\">upload-json-to-convert-to-csv.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;?php\nif (! 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;';\n}\n?&gt;\n&lt;HTML&gt;\n&lt;head&gt;\n&lt;title&gt;Convert JSON to CSV&lt;\/title&gt;\n&lt;style&gt;\nbody { font-family: arial;\n} input[type=\"file\"] { padding: 5px 10px; margin: 30px 0px; border: #666 1px solid; border-radius: 3px;\n}\ninput[type=\"submit\"] { padding: 8px 20px; border: #232323 1px solid; border-radius: 3px; background: #232323; color: #FFF;\n}\n&lt;\/style&gt;\n&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;\n&lt;\/body&gt;\n&lt;\/HTML&gt;\n<\/code><\/pre>\n<p><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/php-json-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\/convert-php-json-to-csv\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on March 7th, 2023. This tutorial gives examples for converting a PHP JSON variable content into a CSV file. This quick example achieves it in a few steps. It uses the PHP fputcsv() method to prepare the CSV output. It reads the input JSON and decodes it into an array. Iterate [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":132288,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-132287","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\/132287","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=132287"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/132287\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/132288"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=132287"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=132287"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=132287"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}