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.

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:

Products CSV - Clue Mediator
Products CSV – Clue Mediator

Let’s start to read data from CSV and convert it into JSON.

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.

That’s it for today.
Thank you for reading. Happy Coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *