Convert CSV to JSON using PHP

Convert CSV to JSON using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Convert CSV to JSON using PHP

Converting a CSV file to JSON is a common requirement when integrating legacy data sources with modern APIs. The goal is often straightforward: read the comma-separated values, map them to an array structure, and output valid JSON. However, as seen in typical debugging scenarios, the issue rarely lies in the logic of the conversion itself. Instead, it usually stems from how the resulting PHP variable is handled during the output phase.

Consider a scenario where you have successfully parsed a file named 1_23.csv. The parsing logic involves opening the file handle, extracting headers with fgetcsv(), and then iterating through the data rows using a nested loop to populate an associative array structure. This approach builds a multidimensional array where keys correspond to column names and values are sub-arrays containing row data.

If you inspect this intermediate state using print_r($result), you will see a populated array structure similar to what is expected:

Array (
    [Inventory] => Array (
        [0] => bs-0468R(20ug)
        [1] => bs-1338R(1ml)
        // ... more rows
    )
)

At this stage, the data transformation is complete. The variables hold the correct values, and no errors are thrown by the fgetcsv() or the array manipulation logic. When you proceed to call json_encode($result), PHP generates a string representation of that JSON object. For example, if $result contains the "Inventory" key with an array of items, json_encode() will return a string like {"Inventory":["bs-0468R(20ug)",...]} .

The problem arises when you attempt to echo this result directly within a PHP file without any additional context. If you run the script from the command line or in a CLI environment, and there is no output buffering configured, the string might appear empty if not handled correctly, though usually, it simply prints the JSON string as text. However, the specific symptom described—seeing nothing on the screen while print_r works perfectly—is often due to how the browser interprets raw JSON versus HTML content.

When you run a script that outputs raw JSON without specifying a content type, modern browsers may not display it as expected depending on how the response is served, or they might wait for more data if the stream isn't flushed. More critically, if the output is intended to be consumed by another API or script, simply echoing the string is correct. But if you are viewing this in a browser and expecting formatted HTML, a raw JSON blob will just look like plain text, which can sometimes be confusing if mixed with whitespace issues.

The most robust solution involves explicitly setting the HTTP response header to inform the client that the content is JSON. Without this header, browsers might try to render the JSON as text or apply their own default formatting, leading to unexpected blank screens or garbled output in certain contexts. You can fix this by adding header('Content-Type: application/json'); before echoing the encoded string.

<?php 
// ... (parsing logic) ...

$json = json_encode($result);

// Ensure the browser treats this as JSON data, not HTML or plain text
header('Content-Type: application/json');

echo $json;
?>

This single line resolves the visibility issue by ensuring the server explicitly declares the content type. Additionally, verify that $file_path is correct and accessible. If the file does not exist at C:\\Users\\bheng\\Desktop\\qb\\1_23.csv, the script would fail silently if error reporting is not enabled, or it might throw a fatal error depending on your configuration. Ensure that the file exists before attempting to open it.

For larger projects or when working within the Laravel ecosystem, you might prefer using the Carbon library for date manipulation or leveraging existing packages like maatwebsite/excel if CSV parsing needs to be more robust than native functions allow. However, for simple conversions, the native PHP stream wrapper combined with proper HTTP headers remains the most efficient and dependency-free approach.

Our network