0

I'd like to convert JSON to CSV file. Here's my PHP code :

<?php
$response = '[{
    "field1": "vala1",
    "field2": "vala2",
    "field3": "vala3",
    "field4": [{
        "field4a": "vala4-1",
        "field4b": "vala4-2",
        "field4c": "vala4-3"
    }]
}, {
    "field1": "valb1",
    "field2": "valb2",
    "field3": "valb3",
    "field4": [{
        "field4a": "valb4-1",
        "field4b": "valb4-2",
        "field4c": "valb4-3"
    }]
}]';

$list = json_decode($response, true);
$fp = fopen('test_json.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields, ';');
}

fclose($fp); 
?>

But, I get this notice:

Array to string conversion

In my CSV file I get Array value in fourth column.

Here's expected output:

vala1;vala2;vala3;vala4-1,vala4-2,vala4-3
valb1;valb2;valb3;valb4-1,valb4-2,valb4-3

I can get expected value if I use this code :

    echo $fields['field1'] . ';' . $fields['field2'] . ';' . $fields['field3'] . ';' . $fields['field4'][0]['field4a'] . ',' . $fields['field4'][0]['field4b'] . ',' . $fields['field4'][0]['field4c'] . '<br>';

But it's not flexible.. So, how to convert subarray json to CSV file that works even if I add many fields in JSON file?

Thanks in advance,

2
  • you're doing a single loop, which means you $fields are the child arrays, which you then try to dump out as a string. you need multiple loops. Commented Jul 13, 2016 at 14:29
  • 2
    Possible duplicate of PHP convert json into csv with sub array Commented Jul 13, 2016 at 14:30

2 Answers 2

1

Edit: I was an idiot and wasn't thinking. The correct answer should be as so:

foreach ($list as $fields) {
    $flatFields = [];
    foreach ($fields as $value) {
        $newValue = $value;
        if (isset($value[0]) && is_array($value[0])) {
            $newValue = implode(',', $value[0]);
        }
        $flatFields[] = $newValue;
    }
    fputcsv($fp, $flatFields, ';');
}

Haven't tested yet but should be fine. If, however, your subarrays also contain subarrays, you'll need a recursive function to handle it - let me know and I'll update this answer.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Sworrub for your response, but I get this error : fputcsv() expects parameter 2 to be array
Thanks again, but I get this error: Parse error: syntax error, unexpected '$value' (T_VARIABLE) . I'm very sorry... Thanks :)
Oops, missed a comma, should be $newValue = implode(',', $value); I'll actually run the code before I make the edit this time to make sure I've not missed anything else :P
I missed something else too, didn't realise your subarrays were JSON objects themselves so I've had to use $value[0] to get those objects instead. Check the edit, I've ran it now and it works.
0

Try this:

...
    $list = json_decode($response, true);
    $fp = fopen('test_json.csv', 'w');

    foreach ($list as $fields) {
        $fields['field4'] = implode(',',$fields['field4']);
        fputcsv($fp, $fields, ';');
    }

    fclose($fp); 

1 Comment

This will only work if the subarrays are always in field4, I'm guessing that this is not always the case. Also, it should be $fields['field4'][0] due to the structure of his JSON - I made this mistake in my answer too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.