Converting json to csv returns array,array - php

I'm trying to convert a json file to csv but only the text "array,array" gets printed in the csv file. I'm guessing this is because multiple arrays get returned but as a noob i dont know how to fix this.
<?php
$jsonString = file_get_contents("data.json");
//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);
$jsonDecoded = $jsonDecoded;
//Give our CSV file a name.
$csvFileName = 'example.csv';
//Open file pointer.
$fp = fopen($csvFileName, 'w');
//Loop through the associative array.
foreach($jsonDecoded as $row){
//Write the row to the CSV file.
fputcsv($fp, $row);
}
//Finally, close the file pointer.
fclose($fp);
print $jsonDecoded;
echo json_last_error_msg();
?>
The json looks like this, contains multiple records and should be printed each on a row.
{"data":[{"ID":4,"UUID":"53F","A schematic overview of your activities":"Yes","Q1_1-1":"To some extent","Q1_1-2":"To some extent","Q1_1-3":"To some extent","Question 1_2":"Yes","Q1_2-1":"Yes","Q1_2-2":"To some extent","Q1_2-3":"No","Q1_2-4":"Yes","Q1_2-5":"To some extent","Q1_2-6":"Yes","Question 1_3":"Yes","Q1_3-1":"Yes","Q1_3-2":"To some extent","Q1_3-3":"To some extent","Q1_3-4":"No","Q1_3_5":"Yes","Question 2":"To some extent","Q2_2":"To some extent","Q2_3":"To some extent","Q2_4":"To some extent","Question 3":"No","Q3_2":"No","Q3_3":"To some extent","Q3_4":"Yes","Question 3_2":"Yes","Q3_2-2":"Yes","Q3_2-3":"To some extent","Question 3_3":"No","Q3_3-2":"To some extent","Q3_3-3":"Yes","Q3_3-4":"To some extent","Question 3_4":"Yes","Q3_4-2":"To some extent","Q3_4-3":"To some extent","Q3_4-4":"To some extent","Question 3_5":"Yes","Q3_5-2":"To some extent","Q3_5-3":"Yes","Q3_5-4":"Yes","Q3_5_5":"To some extent","Q3_5-6":"To some extent","Question 3_6":"Yes","Q3_6-2":"Yes","CreatedAt":"2019-08-14T10:38:07.033Z","CreatedBy":"qqq","UpdatedAt":null,"UpdatedBy":null,"CreatedByID":20,"UpdatedByID":null},{"ID":5,"UUID":"2D40","A schematic overview of your activities":"Yes","Q1_1-1":"To some extent","Q1_1-2":"To some extent","Q1_1-3":"Yes","Question 1_2":"Yes","Q1_2-1":"To some extent","Q1_2-2":"No","Q1_2-3":"To some extent","Q1_2-4":"Yes","Q1_2-5":"Yes","Q1_2-6":"To some extent","Question 1_3":null,"Q1_3-1":null,"Q1_3-2":null,"Q1_3-3":null,"Q1_3-4":null,"Q1_3_5":null,"Question 2":null,"Q2_2":null,"Q2_3":null,"Q2_4":null,"Question 3":"No","Q3_2":"To some extent","Q3_3":"To some extent","Q3_4":"To some extent","Question 3_2":"Yes","Q3_2-2":"To some extent","Q3_2-3":"Yes","Question 3_3":"Yes","Q3_3-2":"No","Q3_3-3":"To some extent","Q3_3-4":"Yes","Question 3_4":"Yes","Q3_4-2":"To some extent","Q3_4-3":"Yes","Q3_4-4":"Yes","Question 3_5":"No","Q3_5-2":"To some extent","Q3_5-3":"To some extent","Q3_5-4":"Yes","Q3_5_5":"To some extent","Q3_5-6":"To some extent","Question 3_6":"Yes","Q3_6-2":"To some extent","CreatedAt":"2019-08-19T13:48:22.770Z","CreatedBy":"qqq","UpdatedAt":null,"UpdatedBy":null,"CreatedByID":20,"UpdatedByID":null}]}

You just need to refer to the 'data' key.
foreach($jsonDecoded['data'] as $row){ ...

https://www.php.net/manual/en/splfileobject.fputcsv.php
$jsonString = file_get_contents("data.json");
//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);
$list= $jsonDecoded;
file = new SplFileObject('example.csv', 'w');
foreach ($list as $fields) {
$file->fputcsv($fields);
}

Related

PHP input to JSON file and JSON file to PHP output

Can anyone please shows me how to get the input of PHP to JSON file (.json) and read data from JSON file and display in PHP (Echo).
for example:
$myObj->name = "John";
$myObj->age= 20;
to result.json
{"name":"John","Age":20}
and retrieve from result.json and display data in PHP as
name=John
Age=20
To convert the object to json use this:
$json = json_encode($myObj);
See the json_encode docs.
To return it back to the format you want try this...
$obj = json_decode($json);
$name = $obj->name; // John
$age = $obj->age; // 20
See the json_decode docs.
To iterate over keys and values do something like this:
foreach($obj as $key=>$value)
{
echo $key . " = " . $value . "\n";
}
json_encode() is used for encoding PHP data into a JSON format and json_decode() is used to decode JSON into a PHP data
json_encode documentation:
http://php.net/manual/en/function.json-encode.php
json_decode documentation
http://php.net/manual/en/function.json-decode.php
if you are having an php array you can convert it into json.
$json_string = json_encode($array);
and write this into a json file.
$fp = fopen('results.json', 'w');
fwrite($fp, json_string);
fclose($fp);
now convert your json string which is in results.json to array.
$str = file_get_contents('./results.json');
$array = json_decode($str, true); // decode the JSON into an associative array

writing all files in directory to json

I made simple text editor and now working on image upload and image manager. I have set up manager to read .json file with all images and it works ok. The problem is for php script to actually write newly added images to that json.
$file = "images.json";
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
$arr_data = array(
'link' => $image,
'tag' => 'images',
);
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$jsondata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));
I am getting
Warning: array_push() expects parameter 1 to be array
even tho array data is provided. How to solve this?
If you are starting with an empty file i.e. images.json then the first time you run these 2 lines
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
the second line will change $arr_data into a boolean probably. As json_decode() will fail to convert nothing into an array.
So add this to initialize the file for use
<?php
$file = "images.json";
file_put_contents($file, '[]'); // init the file
You are also reusing the $arr_data variable so amend this also and you are overwriting the new array as well
$file = "images.json";
file_put_contents($file, '[]'); // init the file
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
// amended to not reuse $arr_data
// ameded to not overwrite the array as you build it
$new_arr[] = array( 'link' => $image, 'tag' => 'images');
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$new_arr);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));

Convert JSON to CSV and save from browser to computer

I have this JSON:
{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}
How to convert this to CSV file or Exel XLS using php pdo?
Also in this example:
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));
}
where I need to put my $jsonTable ?
Use JSON2CSV
A simple PHP script to convert JSON data to CSV
example usage:
php json2csv.php --file=/path/to/source/file.json --dest=/path/to/destination/file.csv
OR You can have it dump the CSV file relative to the PHP script:
php json2csv.php --file=/path/to/source/file.json
I am not sure about the pdo part, but to write it to a file you would do something like this
$json = '{"data":[{"ID":1,"br":"1-2015","kupac":"ADAkolor","datum":"2015-05-19","rok":"2015-05-21","status":"placeno"},{"ID":2,"br":"2-2015","kupac":"Milenk","datum":"2015-05-27","rok":"2015-05-28","status":""}]}';
$out = fopen('file.csv', 'w');
foreach(json_decode($json, true)['data'] as $key => $value) {
fputcsv($out, $value);
}
fclose($out);

PHP export JSON to CSV

Im try export json result to csv and save data as file, im try with something like this
$getFile = file_get_contents('JSON_URL');
$json_obj = json_decode($getFile);
$fp = fopen('/home/xxxx/public_html/xxxx/api/export/tmp/file.csv', 'w');
foreach ($json_obj as $row) {
fputcsv($fp, $row);
}
fclose($fp);
but seems not working
Here's an example json format for link above
[
{key:value,key:value...}
...]
in order for your code to work as expected, try decoding the json object as an associative array. This is done by passing a boolean true to the 2nd param of json_decode
$json_obj = json_decode($getFile, true);

how to retrieve array value using php

I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.
make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html

Categories