[Tut] Convert PHP CSV to JSON - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] Convert PHP CSV to JSON (/thread-101203.html) |
[Tut] Convert PHP CSV to JSON - xSicKxBot - 08-12-2023 [Tut] Convert PHP CSV to JSON <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/03/convert-php-csv-to-json.jpg" width="550" height="417" title="" alt="" /></div><div><div class="modified-on" readability="7.0909090909091"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on March 17th, 2023.</div> <p>JSON format is a widely used format while working with API development. Most of the existing API responses are in JSON format.</p> <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> <h2>Quick example</h2> <pre class="prettyprint"><code class="language-php"><?php $csvFileContent= file_get_contents("animals.csv"); // Converts the CSV file content into line array $csvLineArray = explode("\n", $csvFileContent); // Forms row results in an array format $result = array_map("str_getcsv", $csvLineArray); $jsonObject = json_encode($result); print_r($jsonObject); ?> </code></pre> <p>The above quick example in PHP converts the CSV file content into JSON with few lines of code.</p> <ol> <li>First, it reads the .csv file content using the PHP file_get_contents() function.</li> <li>It explodes the CSV row by the new line (\n) escape sequence.</li> <li>Then, it iterates the line array and reads the line data of the CSV row.</li> <li>Finally, the resultant CSV row array is converted to JSON using the json_encode() function.</li> </ol> <p>In step 3, the iteration happens with a single line of code. This line maps the array to call PHP <code class="language-php">str_getcsv</code> to parse and convert the CSV lines into an array.</p> <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> <p>The below input file is saved and used for this PHP example.</p> <p><strong>Input CSV</strong></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><strong>Output JSON</strong></p> <p>This PHP quick example displays the below JSON output on the browser.</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>In the following sections, we will see two more examples of converting CSV files into JSON.</p> <ol> <li>Method 2: Convert CSV (containing header) into a JSON (associating the column=>value pair)</li> <li>Method 3: Upload a CSV file and convert it into JSON</li> </ol> <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="(max-width: 550px) 100vw, 550px"></p> <h2>Method 2: Convert CSV (containing header) into a JSON (associating the column=>value pair)</h2> <p>This example uses a CSV string as its input instead of a file.</p> <p>It creates the header column array by getting the first row of the CSV file.</p> <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> <p>This loop prepares an associative array containing the CSV data.</p> <p>In the final step, the json_encode() function converts the associative array and writes it into an output JSON file.</p> <pre class="prettyprint"><code class="language-php"><?php $csvString = "Id,Name,Type,Role 1,Lion,Wild,Boss 2,Tiger,Wild,CEO 3,Jaguar,Wild,Developer"; $lineContent = array_map("str_getcsv", explode("\n", $csvString)); $headers = $lineContent[0]; $jsonArray = array(); $rowCount = count($lineContent); for ($i=1;$i<$rowCount;$i++) { foreach ($lineContent[$i] as $key => $column) { $jsonArray[$i][$headers[$key]] = $column; } } header('Content-type: application/json; charset=UTF-8'); $fp = fopen('animals.json', 'w'); fwrite($fp, json_encode($jsonArray, JSON_PRETTY_PRINT)); fclose($fp); ?> </code></pre> <h3>Output – The animal.json file</h3> <p>This is the output written to the animal.json file via this PHP program.</p> <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" } } </code></pre> <h2>Method 3: Upload a CSV file and convert it into JSON</h2> <p>Instead of using a fixed CSV input assigned to a program, this code allows users to choose the CSV file.</p> <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> <p>Once uploaded, the PHP script will read the CSV file content, prepare the array, and form the JSON output.</p> <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> <p class="code-heading">upload-and-convert-csv-to-json.php</p> <pre class="prettyprint"><code class="language-php-template"><?php if (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 < $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'; } } ?> <!DOCTYPE html> <html> <head> <title>Convert CSV to JSON</title> <style> 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; } </style> </head> <body> <form name="frmUpload" method="post" enctype="multipart/form-data"> <input type="file" name="csv_file_input" accept=".csv" /> <input type="submit" name="convert" value="Convert"> <?php if (!empty($error)) { ?> <span class="validation-message"><?php echo $error; ?></span> <?php } ?> </form> </body> </html> </code></pre> <p><strong>Output:</strong></p> <p>This program writes the output JSON into a file and downloads it automatically to the browser.</p> <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="(max-width: 550px) 100vw, 550px"><br /><a class="download" href="https://phppot.com/downloads/php/php-csv-to-json.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-csv-to-json/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2023/03/17/convert-php-csv-to-json/ |