{"id":132530,"date":"2023-03-17T15:52:14","date_gmt":"2023-03-17T15:52:14","guid":{"rendered":"https:\/\/phppot.com\/?p=20589"},"modified":"2023-03-17T15:52:14","modified_gmt":"2023-03-17T15:52:14","slug":"convert-php-csv-to-json","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/03\/17\/convert-php-csv-to-json\/","title":{"rendered":"Convert PHP CSV to JSON"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.0909090909091\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on March 17th, 2023.<\/div>\n<p>JSON format is a widely used format while working with API development. Most of the existing API responses are in JSON format.<\/p>\n<p>Converting CSV content into a JSON format is simple in PHP. In this article, we will see different methods of achieving this conversion.<\/p>\n<h2>Quick example<\/h2>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php $csvFileContent= file_get_contents(\"animals.csv\");\n\/\/ Converts the CSV file content into line array $csvLineArray = explode(\"\\n\", $csvFileContent);\n\/\/ Forms row results in an array format\n$result = array_map(\"str_getcsv\", $csvLineArray);\n$jsonObject = json_encode($result);\nprint_r($jsonObject);\n?&gt;\n<\/code><\/pre>\n<p>The above quick example in PHP converts the CSV file content into JSON with few lines of code.<\/p>\n<ol>\n<li>First, it reads the .csv file content using the PHP file_get_contents() function.<\/li>\n<li>It explodes the CSV row by the new line (\\n) escape sequence.<\/li>\n<li>Then, it iterates the line array and reads the line data of the CSV row.<\/li>\n<li>Finally, the resultant CSV row array is converted to JSON using the json_encode() function.<\/li>\n<\/ol>\n<p>In step 3, the iteration happens with a single line of code. This line maps the array to call&nbsp; PHP <code class=\"language-php\">str_getcsv<\/code> to parse and convert the CSV lines into an array.<\/p>\n<p>When we saw the <a href=\"https:\/\/phppot.com\/php\/php-csv-file-read\/\">methods of reading a CSV file<\/a>, we created an example using <code class=\"language-php\">str_getcsv<\/code> function.<\/p>\n<p>The below input file is saved and used for this PHP example.<\/p>\n<p><strong>Input CSV<\/strong><\/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><strong>Output JSON<\/strong><\/p>\n<p>This PHP quick example displays the below JSON output on the browser.<\/p>\n<pre class=\"prettyprint\"><code>[[\"Id\",\"Name\",\"Type\",\"Role\"],[\"1\",\"Lion\",\"Wild\",\"Lazy Boss\"],[\"2\",\"Tiger\",\"Wild\",\"CEO\"],[\"3\",\"Jaguar\",\"Wild\",\"Developer\"]]\n<\/code><\/pre>\n<p>In the following sections, we will see two more examples of converting CSV files into JSON.<\/p>\n<ol>\n<li>Method 2: Convert CSV (containing header) into a JSON (associating the column=&gt;value pair)<\/li>\n<li>Method 3: Upload a CSV file and convert it into JSON<\/li>\n<\/ol>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-20597\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/upload-and-convert-csv-to-json-550x417.jpg\" alt=\"upload and convert csv to json\" width=\"550\" height=\"417\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/upload-and-convert-csv-to-json-550x417.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/upload-and-convert-csv-to-json-300x228.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/upload-and-convert-csv-to-json-768x582.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/upload-and-convert-csv-to-json.jpg 1200w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>Method 2: Convert CSV (containing header) into a JSON (associating the column=&gt;value pair)<\/h2>\n<p>This example uses a CSV string as its input instead of a file.<\/p>\n<p>It creates the header column array by getting the first row of the CSV file.<\/p>\n<p>Then, the code iterates the CSV rows from the second row onwards. On each iteration, it associates the header column and the iterated data column.<\/p>\n<p>This loop prepares an associative array containing the CSV data.<\/p>\n<p>In the final step, the json_encode() function converts the associative array and writes it into an output JSON file.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">&lt;?php\n$csvString = \"Id,Name,Type,Role\n1,Lion,Wild,Boss\n2,Tiger,Wild,CEO\n3,Jaguar,Wild,Developer\"; $lineContent = array_map(\"str_getcsv\", explode(\"\\n\", $csvString)); $headers = $lineContent[0];\n$jsonArray = array();\n$rowCount = count($lineContent);\nfor ($i=1;$i&lt;$rowCount;$i++) { foreach ($lineContent[$i] as $key =&gt; $column) { $jsonArray[$i][$headers[$key]] = $column; }\n} header('Content-type: application\/json; charset=UTF-8');\n$fp = fopen('animals.json', 'w');\nfwrite($fp, json_encode($jsonArray, JSON_PRETTY_PRINT));\nfclose($fp);\n?&gt;\n<\/code><\/pre>\n<h3>Output \u2013 The animal.json file<\/h3>\n<p>This is the output written to the animal.json file via this PHP program.<\/p>\n<pre class=\"prettyprint\"><code>{ \"1\": { \"Id\": \"1\", \"Name\": \"Lion\", \"Type\": \"Wild\", \"Role\": \"Boss\" }, \"2\": { \"Id\": \"2\", \"Name\": \"Tiger\", \"Type\": \"Wild\", \"Role\": \"CEO\" }, \"3\": { \"Id\": \"3\", \"Name\": \"Jaguar\", \"Type\": \"Wild\", \"Role\": \"Developer\" }\n}\n<\/code><\/pre>\n<h2>Method 3: Upload a CSV file and convert it into JSON<\/h2>\n<p>Instead of using a fixed CSV input assigned to a program, this code allows users to choose the CSV file.<\/p>\n<p>This code shows an <a href=\"https:\/\/phppot.com\/php\/working-on-file-upload-using-php\/\">HTML form with a file input to upload<\/a> the input CSV file.<\/p>\n<p>Once uploaded, the PHP script will read the CSV file content, prepare the array, and form the JSON output.<\/p>\n<p>In a previous tutorial, we have seen how to <a href=\"https:\/\/phppot.com\/php\/php-csv-to-array\/\">convert a CSV into a PHP array<\/a>.<\/p>\n<p class=\"code-heading\">upload-and-convert-csv-to-json.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php-template\">&lt;?php\nif (isset($_POST[\"convert\"])) { if ($_FILES['csv_file_input']['name']) { if ($_FILES['csv_file_input'][\"type\"] == 'text\/csv') { $jsonOutput = array(); $csvFileContent = file_get_contents($_FILES['csv_file_input']['tmp_name']); $result = array_map(\"str_getcsv\", explode(\"\\n\", $csvFileContent)); $header = $result[0]; $recordCount = count($result); for ($i = 1; $i &lt; $recordCount; $i++) { \/\/ Associates the data with the string index in the header array $data = array_combine($header, $result[$i]); $jsonOutput[$i] = $data; } header('Content-disposition: attachment; filename=output.json'); header('Content-type: application\/json'); echo json_encode($jsonOutput); exit(); } else { $error = 'Invalid CSV uploaded'; } } else { $error = 'Invalid CSV uploaded'; }\n}\n?&gt;\n&lt;!DOCTYPE html&gt;\n&lt;html&gt; &lt;head&gt; &lt;title&gt;Convert CSV to JSON&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; } .validation-message { color: #e20900; } &lt;\/style&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;form name=\"frmUpload\" method=\"post\" enctype=\"multipart\/form-data\"&gt; &lt;input type=\"file\" name=\"csv_file_input\" accept=\".csv\" \/&gt; &lt;input type=\"submit\" name=\"convert\" value=\"Convert\"&gt; &lt;?php if (!empty($error)) { ?&gt; &lt;span class=\"validation-message\"&gt;&lt;?php echo $error; ?&gt;&lt;\/span&gt; &lt;?php } ?&gt; &lt;\/form&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p>This program writes the output JSON into a file and downloads it automatically to the browser.<\/p>\n<p>Note: Both methods 2 and 3 require CSV input with a header column row to get good results.<br \/><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-20600\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/output-json-file-550x147.jpg\" alt=\"output json file\" width=\"550\" height=\"147\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/output-json-file-550x147.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/output-json-file-300x80.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2023\/03\/output-json-file.jpg 600w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php\/php-csv-to-json.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-csv-to-json\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on March 17th, 2023. JSON format is a widely used format while working with API development. Most of the existing API responses are in JSON format. Converting CSV content into a JSON format is simple in PHP. In this article, we will see different methods of achieving this conversion. Quick example [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":132531,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-132530","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\/132530","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=132530"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/132530\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/132531"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=132530"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=132530"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=132530"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}