I have generated json output using API and now I have to save this output in csv file in below structure- The column names are litle bit different from the actual name. Some records are coming as null.
Example:
json_data =
"data": [
{
"id": 1000001,
"version_modified_date__v": "2022-03-01T08:23:04.000Z",
"doc_roles__sysr": {
"responseDetails": {
"pagesize": 250,
"pageoffset": 0,
"size": 22,
"total": 22
},
"data": [
{
"role_name__sys": "emea_project_owner__c",
"user__sys": 3566601,
"group__sys": null
},
{
"role_name__sys": "emea_submitter__c",
"user__sys": 3566601,
"group__sys": null
}
]
}
},
{
"id": 1000002,
"version_modified_date__v": "2021-02-24T17:58:05.000Z",
"doc_roles__sysr": {
"responseDetails": {
"pagesize": 250,
"pageoffset": 0,
"size": 9,
"total": 9
},
"data": [
{
"role_name__sys": "owner__c",
"user__sys": 8272503,
"group__sys": null
},
{
"role_name__sys": "reference_specialist__c",
"user__sys": null,
"group__sys": 1461227836262
}
]
}
}
]
I want in CSV file in below format -
id version_modified_date role name user id group
1000001 2022-03-01T08:23:04.000Z emea_project_owner__c 3566601
1000001 2022-03-01T08:23:04.000Z emea_submitter__c 3566601
1000002 2021-02-24T17:58:05.000Z owner__c 8272503
1000002 2021-02-24T17:58:05.000Z reference_specialist__c 1461227836262
I tried below code but didn't get any luck. Please help me to correct this code-
$content = json_decode(json_encode($content), true);
$fp = fopen('doc_roles__sys.csv', 'w');
foreach ($content['data'] as $item) {
$output['id'] = $item['id'];
$output['version_modified_date'] = $item['version_modified_date__v'];
$output['role name'] = $item['data'][0]['role_name__sys'];
$output['user id'] = $item['data'][0]['user__sys'];
$output['group'] = $item['data'][0]['group__sys'];
//$output['document_id'] = $item['data'][0]['document_id'];
foreach ($output as $line) {
fputcsv($fp, $item);
}
}
echo $output;
//$fp = fopen('doc_roles__sys.csv', 'a');
//foreach ($output as $line) {
// fputcsv($fp, $item);
//}
fclose($fp);
The output I am getting from above code is -
1077079,Array
1077079,Array
1077079,Array
1077079,Array
1077079,Array