How to pass JSON data to CSV using PHP – Programming Code Examples
PHP

How to pass JSON data to CSV using PHP3 min read

But since I already talked about how to consume webservices (whether REST or SOAP) I am going to focus on the part that caught my attention: how to go from JSON to CSV.

Let’s clarify the many before going to the details:

What is JSON




JSON stands for JavaScript Object Notation, that is: JavaScript object notation. It’s beyond the scope of this article (and this blog in general) to talk about the benefits (or lack thereof) of JavaScript… there’s a lot of great stuff out there.

The point is that regardless of what you like or dislike, JavaScript has a very handy syntax for describing objects: anything enclosed in {} is an object (with the possible exception of function bodies). …).

This makes it an extremely convenient format for the exchange of information on complex structures, since it is a very simple way to go from an object in memory to a textual representation (which can be sent through a text exchange protocol… by HTTP example :)).

In short, a text that looks like this:

It would be representing an object with two properties: name and friends. The first is a string, the second is an array of other objects.

More information here.

It looks very simple (and it is!) but it has a small drawback: its syntax is very non-permissive (Leave one, drop and hold on :p), therefore, it is very convenient to use PHP’s own functions to manipulate it ( json_encode and json_decode).

And here it makes me a bit nostalgic to talk about the older post I wrote for this blog, but I think knowing how to iterate over a JSON using PHP can contribute to the answer.

What is CSV

CSV stands for Comma Separated Values. It is a text format that is also used for the exchange of information between systems.

Usually the content of this type of file is a succession of rows that correspond to records whose number of fields can vary from one to another and the length of each field also varies.

Example:

From JSON to CSV

A first caveat that must be made is that JSON is a format that allows complex structures (multilevel for example), while CSV is a much simpler format (it is based on “flat” structures), with which, something is will lose along the way (or some assumption or transformation of the information will have to be made).

For practical purposes, let’s assume that the starting JSON is single level, something like:

The corresponding CSV would be:

A PHP code that achieves that is:

Now, if the need is more complex… nothing better than searching a bit :).

Leave a Comment