3

I have a simple PHP code to save JSON to CSV , but I have an error, this the code:

<?php
$inputJSON = file_get_contents('https://url');

$out = fopen('C:\xampp\htdocs\tkp_product\tkp2.csv', 'w');
foreach(json_decode($inputJSON, true)["data"] as $key => $value) {
  fputcsv($out, $value);
}
fclose($out);

?>

This for error for fputcsv($out, $value);

Notice: Array to string conversion in C:\xampp\htdocs\tkp.php on line 6

Notice: Array to string conversion in C:\xampp\htdocs\tkp.php on line 6

I'm running this script using XAMPP in Win 10 with PHP7 installed. What should I do to resolve this issue?

totymedli
  • 29,531
  • 22
  • 131
  • 165
Alvariko Zion
  • 31
  • 1
  • 3
  • Are the line numbers the same here as in tkp.php? Which line is line 6? – mkasberg Mar 19 '17 at 19:52
  • Wait I'm editing a question – Alvariko Zion Mar 19 '17 at 19:53
  • CSV is a flat format, so `fputcsv`'s second argument is supposed to be a flat array. Your `$value` is an array that contains other arrays. PHP converts them to strings (so that they can be written out as a single CSV field) and emits a notice. – lafor Mar 19 '17 at 20:24

1 Answers1

0

You need to check for type of value

foreach(json_decode($inputJSON, true)["data"] as $key => $value) {
 if(!is_array($value)) fputcsv($out, $value);
}

But note it seems that file_get_contents('https://url'); return a nested arrays, this will get just the first level

Ahmad Rezk
  • 198
  • 1
  • 13
  • fputcsv Not working.. This a sample JSON I'm using https://gist.github.com/anonymous/7b8fe84d482cd7f7b95a13187ae1cac7 – Alvariko Zion Mar 19 '17 at 20:01
  • It seems that your json has more than one level, How can you want save it as CSV ? CSV is line by line structure and json is hierarchy structure so how json converted to csv – Ahmad Rezk Mar 20 '17 at 07:37