PHP convert json to CSV – explained

Sometimes you need to convert a json string to CSV in PHP. For example we want to get the names Norrmalm and Liljeholmen (cities names at Sweden) from the following json string:

  '{"Norrmalm":"502","Liljeholmen":"491"}';

Here is the simplest solution:

$jsonStr='{"Norrmalm":"502","Liljeholmen":"491"}';
$csv = str_replace(array('[',']'), '', json_encode(array_keys(json_decode($jsonStr, true))))
echo $csv;

It will print out :

 "Norrmalm","Liljeholmen"

How it works ?

json_decode($jsonStr, true)
Look at the first inner most parentheses (json_decode), it converts the jsonStr to PHP array like:

 array(
   "Norrmalm"=>"502",
   "Liljeholmen"=>"491",
 );

array_keys(json_decode($jsonStr, true))
Now look at the second inner most parenthesis (array_keys) will return a new array containg only keys of the previous above array, it will look like:

 array(
   "Norrmalm",
   "Liljeholmen",
 );


json_encode(array_keys(json_decode($jsonStr, true)))

Now looking at the third inner most parenthesis (json_encode) will convert the above array to json string, it will add quotation marks arround the values, and will look like:

 
  ["Norrmalm","Liljeholmen"]

str_replace(array(‘[‘,’]’), ”, json_encode(array_keys(json_decode($jsonStr, true))))
Finally looking at the outermost parenthesis (str_replace), because we want to remove the square brackets from the above we need to replace both ‘[‘ and ‘]’ from the above, and this could be achieved by a single str_replace function by providing the search string as an array like array(‘[‘,’]’). So this final function will return the following:

 "Norrmalm","Liljeholmen"

Leave a Reply

Your email address will not be published. Required fields are marked *