Converting CSV to JSON in PHP

Converting a CSV file to JSON can be a useful task in various applications, such as data processing, data visualization, and API integrations. In this article, we will explore how to convert a CSV file to JSON using PHP.

Reading the CSV File

The first step is to read the CSV file using PHP. You can use the fopen function to open the file and the fgetcsv function to read the file row by row.

$csvFile = 'path/to/your/file.csv';
$fp = fopen($csvFile, 'r');
$$data = array();
while (($row = fgetcsv($fp, 0, ",")) !== FALSE) {
    $data[] = $row;

In this code, we open the CSV file in read mode ('r') and initialize an empty array $data to store the data. The fgetcsv function reads the file row by row, and we store each row in the $data array.

Converting CSV to JSON

Once we have the data in the $data array, we can convert it to JSON using the json_encode function.

$jsonData = json_encode($data);

The json_encode function takes the $data array as input and returns a JSON-encoded string.

Outputting the JSON Data

Finally, we can output the JSON data to the screen or save it to a file.

echo $jsonData;

Alternatively, you can save the JSON data to a file using the file_put_contents function.

$jsonFile = 'path/to/your/file.json';
file_put_contents($jsonFile, $jsonData);
Commabot Technologies, 2024