This is a short tutorial on how to convert the data in a CSV file into a JSON string format. For this example, we will assume that we have a CSV file called names.csv and that it contains the following data:
As you can see – it’s pretty simple and straight-forward. To convert it into JSON, we will need to read the CSV file using PHP before converting it into JSON.
Here’s a quick example using the CSV file above:
Explained:
- We opened our CSV file using the fopen function. We set the second parameter to “r” because we only need to read the file – not modify it.
- We created a PHP array called $csvData. This array will contain the data from our CSV file.
- We looped through the rows in our CSV file using the fgetcsv function and added them to our $csvData array.
- Finally, once our loop is completed, we convert the CSV data into a JSON string by using the function json_encode.
0 comments:
Post a Comment