Когда я запускаю приведенный ниже код, он приводит к первой строке в длинном списке столбцов, содержащих только текст массив.
Я использовал $decoded = json_decode($json_file, true);
чтобы указать, что я хочу массивы вместо объектов, поэтому я не уверен, в чем проблема.
Должен ли я использовать скобки или обозначение стрелки где-то, чтобы указать, что я хочу значения массива?
$json_file = file_get_contents('https://fakeurl.com&contentType=json', false);
$decoded = json_decode($json_file, true);
$fp = fopen('output.csv', 'w');
foreach($decoded as $comment) {
fputcsv($fp, $comment);
}
fclose($fp);
Вот небольшой фрагмент JSON. Это выглядит так:
{
"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 will be emailed to the address you submitted. This donation is tax-deductible to the fullest extent of the law.",
"type": "xs:string",
"format": ""}]
}]
}
Ваш массив намного глубже, и значения должны быть извлечены:
foreach($decoded['rows'] as $row) {
$values = array_column($row['columns'], 'value');
fputcsv($fp, $values);
}
Если вы хотите, чтобы имена / заголовки были в первой строке, вам нужно сделать это до цикла:
$headers = array_column($decoded['rows'][0]['columns'], 'name');
fputcsv($fp, $headers);
Других решений пока нет …