JSON format is a widely used format when dealing with API development. Most of the existing API responses are in JSON format.
Converting CSV content to JSON format in PHP is easy. In this article, we will look at various methods of achieving this conversion.
<?php
$csvFileContent= file_get_contents("example.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);
?>
The above quick example in PHP converts the CSV file content into JSON with few lines of code.
- First, it reads the .csv file content using the PHP file_get_contents() function.
- It explodes the CSV row by the new line (\n) escape sequence.
- Then, it iterates the line array and reads the line data of the CSV row.
- Finally, the resultant CSV row array is converted to JSON using the json_encode() function.
In step 3, the iteration happens with a single line of code. This line maps the array to call PHP str_getcsv
to parse and convert the CSV lines into an array.
The below input file is saved and used for this PHP example.
Input CSV
Id,Name,Type,Role
1,Lion,Wild,"Lazy Boss"
2,Tiger,Wild,CEO
3,Jaguar,Wild,Developer
Output JSON
This PHP quick example displays the below JSON output on the browser.
[["Id","Name","Type","Role"],["1","Lion","Wild","Lazy Boss"],["2","Tiger","Wild","CEO"],["3","Jaguar","Wild","Developer"]]