Converting JSON from URL to CSV with PHP -
when run code below results in first row in long list of columns containing text array.
i've used $decoded = json_decode($json_file, true);
indicate want arrays instead of objects i'm not sure issue is.
should using bracket or arrow notation somewhere specify want array values?
$json_file = file_get_contents('https://fakeurl.com&contenttype=json', false); $decoded = json_decode($json_file, true); $fp = fopen('output.csv', 'w'); foreach($decoded $comment) { fputcsv($fp, $comment); } fclose($fp);
here small snippet of json. looks way through:
{ "rows": [{ "columns": [{ "name": "clientid", "value": "1839", "type": "xs:int", "format": "" }, { "name": "campaignid", "value": "25646", "type": "xs:int", "format": "" }, { "name": "campaignstatus", "value": "live", "type": "xs:string", "format": "" }, { "name": "campaignname", "value": "template donation litle", "type": "xs:string", "format": "" }, { "name": "campaignexportname", "value": "template donation litle", "type": "xs:string", "format": "" }, { "name": "description", "value": "/donate/template/litle", "type": "xs:string", "format": "" }] }, { "columns": [{ "name": "clientid", "value": "1839", "type": "xs:int", "format": "" }, { "name": "campaignid", "value": "25812", "type": "xs:int", "format": "" }, { "name": "campaignstatus", "value": "live", "type": "xs:string", "format": "" }, { "name": "campaignname", "value": "monthly only", "type": "xs:string", "format": "" }, { "name": "campaignexportname", "value": "monthly only", "type": "xs:string", "format": "" }, { "name": "description", "value": "a donation receipt emailed address submitted. donation tax-deductible fullest extent of law.", "type": "xs:string", "format": "" }] }] }
your array deeper , values need extracted:
foreach($decoded['rows'] $row) { $values = array_column($row['columns'], 'value'); fputcsv($fp, $values); }
if want names/headers in first row need before loop:
$headers = array_column($decoded['rows'][0]['columns'], 'name'); fputcsv($fp, $headers);
Comments
Post a Comment