Convert CSV to JSON in PHP
Today we will show you how to convert CSV to JSON in PHP. Sometimes we need to implement functionality like read data from CSV and upload it in a database at that time you have to convert CSV to JSON.
Convert a CSV to JSON with PHP, CSV to JSON conversion using PHP, Convert a CSV file into JSON using PHP, php convert csv to array, php convert file to json, php csv, wordpress csv to json, php csv import, php stream csv, csv to nested json.
Checkout more articles on PHP
- Remove the last character from a string in PHP
- Sorting Arrays in PHP
- How to use session in PHP
- Replace image src in HTML using PHP
- Explode() and Implode() Function in PHP
To Convert csv data to json, first we need to read the CSV file. Assume that we have CSV file named `products.csv` and that contains below data:
Product Name,SKU,Price
MI,MI123,18990
OPPO,Oppo123,27860
Products CSV - Clue Mediator
Let's start to read data from CSV and convert it into JSON.
<?php
$fileName = "../files/products.csv";
$file = fopen($fileName, "r");
$productData = array();
while (($data = fgetcsv($file, 0, ",")) !== FALSE) {
$productData[] = $data;
}
echo json_encode($productData);
?>
// Output: [["Product Name","SKU","Price"],["MI","MI123","18990"],["OPPO","Oppo123","27860"]]
How It Works:
Using the `fopen` function, we have opened the csv file and set the second parameter `r` to read the file.
Using the `fgetcsv` function, we iterated the rows of the CSV file and added the data into the `$productData` array.
At last, when the loop is completed, we convert the `$productData` array into json using the `json_encode` function.
If you want to ignore the header of CSV i.e, Product Name,SKU,Price then you can do it like this.
<?php
$fileName = "../files/products.csv";
$file = fopen($fileName, "r");
$row=0;
$productData = array();
while (($data = fgetcsv($file, 0, ",")) !== FALSE) {
if($row > 0){
$productData[] = $data;
}
$row++;
}
echo json_encode($productData);
?>
// Output: [["MI","MI123","18990"],["OPPO","Oppo123","27860"]]
That’s it for today.
Thank you for reading. Happy Coding!