Try it yourself with our free Json To Csv tool — runs entirely in your browser, no signup needed.

How to Convert JSON to CSV in PHP

How to Convert JSON to CSV in PHP

Converting JSON data to CSV is a common requirement in many PHP applications, especially when dealing with data imports and exports. JSON (JavaScript Object Notation) is a lightweight data interchange format, while CSV (Comma Separated Values) is a widely used format for tabular data. In this article, we will explore how to convert JSON to CSV in PHP, covering the basics, handling edge cases, and providing performance tips.

Quick Example

Here is a minimal example that converts a JSON string to a CSV string:

<?php
$json = '[{"name":"John","age":30},{"name":"Jane","age":25}]';
$data = json_decode($json, true);
$csv = array();
foreach ($data as $row) {
    $csv[] = implode(',', $row);
}
$csv = implode("\n", $csv);
echo $csv;

This code decodes the JSON string into an array, iterates over the array, and constructs a CSV string by imploding each row with commas and then imploding the rows with newlines.

Step-by-Step Breakdown

Let's walk through the code line by line:

  1. $json = '[{"name":"John","age":30},{"name":"Jane","age":25}]';: This is the JSON string we want to convert.
  2. $data = json_decode($json, true);: We use the json_decode() function to parse the JSON string into a PHP array. The second argument true tells json_decode() to return an associative array instead of an object.
  3. $csv = array();: We initialize an empty array to store the CSV rows.
  4. foreach ($data as $row) { ... }: We iterate over the decoded JSON data using a foreach loop.
  5. $csv[] = implode(',', $row);: Inside the loop, we use the implode() function to concatenate the values of each row with commas.
  6. $csv = implode("\n", $csv);: After the loop, we use implode() again to concatenate the rows with newlines.
  7. echo $csv;: Finally, we output the resulting CSV string.

Handling Edge Cases

Empty/Null Input

If the input JSON string is empty or null, we should handle it gracefully to avoid errors:

$json = '';
if (empty($json)) {
    $csv = '';
} else {
    $data = json_decode($json, true);
    // ...
}

Invalid Input

If the input JSON string is invalid, json_decode() will return null. We can check for this and throw an exception or return an error message:

$json = ' invalid json ';
$data = json_decode($json, true);
if ($data === null) {
    throw new Exception('Invalid JSON input');
}

Large Input

When dealing with large JSON inputs, we should consider memory usage and performance. One approach is to use a streaming JSON parser like JsonMachine:

$fp = fopen('large_json_file.json', 'r');
$parser = new JsonMachine\Parser($fp);
while ($parser->advance()) {
    if ($parser->isStartArray()) {
        // ...
    }
}

You can install JsonMachine using Composer: composer require json-machine/json-machine.

Unicode/Special Characters

When dealing with Unicode or special characters, we should ensure that our CSV output is properly encoded. We can use the fputcsv() function, which handles encoding correctly:

$fp = fopen('output.csv', 'w');
foreach ($data as $row) {
    fputcsv($fp, $row);
}
fclose($fp);

Common Mistakes

1. Not checking for invalid JSON input

// Wrong
$data = json_decode($json, true);
// ...

// Corrected
$data = json_decode($json, true);
if ($data === null) {
    throw new Exception('Invalid JSON input');
}

2. Not handling empty/null input

// Wrong
foreach ($data as $row) { ... }

// Corrected
if (empty($json)) {
    $csv = '';
} else {
    $data = json_decode($json, true);
    // ...
}

3. Not using a streaming parser for large inputs

// Wrong
$data = json_decode(file_get_contents('large_json_file.json'), true);

// Corrected
$fp = fopen('large_json_file.json', 'r');
$parser = new JsonMachine\Parser($fp);
// ...

Performance Tips

1. Use a streaming parser for large inputs

Using a streaming parser like JsonMachine can significantly improve performance when dealing with large JSON inputs.

2. Use fputcsv() for CSV output

The fputcsv() function is optimized for CSV output and handles encoding correctly.

3. Avoid unnecessary memory allocation

When dealing with large inputs, avoid allocating unnecessary memory by using iterative approaches instead of loading the entire data into memory.

FAQ

Q: What is the best way to handle Unicode characters in CSV output?

A: Use the fputcsv() function, which handles encoding correctly.

Q: How can I improve performance when dealing with large JSON inputs?

A: Use a streaming parser like JsonMachine.

Q: What happens if the input JSON string is empty or null?

A: Handle it gracefully by checking for empty or null input and returning an empty CSV string or throwing an exception.

Q: Can I use this code for XML input?

A: No, this code is specifically designed for JSON input. You would need to use a different approach for XML input.

Q: How can I install the JsonMachine library?

A: You can install JsonMachine using Composer: composer require json-machine/json-machine.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp