Convert JSON to CSV and save from browser to computer - php

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);

Related

Build csv and upload to google drive in php (laravel 5.8)

How do I send a response()->stream() to google drive ? I'm not getting it because this method returns a class and not a file. My question is if I will need to save locally using file_put_contents() so that I can then send it to google drive
public function buildCsv($columns, $content): \Closure
{
return function () use ($columns, $content){
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($content as $item) {
fputcsv($file, $item);
}
fclose($file);
};
}
$cb = $this->buildCsv($this->CSVColumns, $csvData);
\Storage::disk('google')->put("csv-test", response()->stream($cb, 200, $headers));
On google drive my file looks like this:
Try this
public function buildCsvFile($columns, $content): string
{
$file = tmpfile();
fputcsv($file, $columns);
foreach ($content as $item) {
fputcsv($file, $item);
}
$metaDatas = stream_get_meta_data($file);
return file_get_contents($metaDatas['uri']);
}
$cb = $this->buildCsv($this->CSVColumns, $csvData);
\Storage::disk('google')->put("csv-test.csv", $cb);

Converting json to csv returns array,array

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);
}

What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?

As the code i tried and by trial removal to get json content out of the return is below
method i used.
$date= YYYYMMDD;
//example '20140113'
$handle = fopen('http://finance.yahoo.com/connection/currency-converter-cache?date='.$date.'', 'r');
//sample code is http://finance.yahoo.com/connection/currency-converter-cache?date=20140208 paste the url in browser;
// use loop to get all until end of content
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
the code return a given bulk in yahoo and json format
so remove the unknown format which is
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
by
$contents = str_replace('/**/YAHOO.Finance.CurrencyConverter.addConversionRates(','',$contents);
$contents = str_replace(');','',$contents);
$obj = json_decode($contents,true);
then loop the content by
foreach($obj['list']['resources'] as $key0 => $value0){
}
I prefer to use file_get_contents to get the html and preg_match_all to cleanup the json, i.e.:
<?php
$json = file_get_contents("http://finance.yahoo.com/connection/currency-converter-cache?date=20140113");
preg_match_all('/\((.*)\);/si', $json, $json, PREG_PATTERN_ORDER);
$json = $json[1][0];
$json = json_decode($json,true);
foreach ($json["list"]["resources"] as $resource){
echo $resource["resource"]["fields"]["date"];
echo $resource["resource"]["fields"]["price"];
echo $resource["resource"]["fields"]["symbol"];
echo $resource["resource"]["fields"]["price"];
}
NOTE:
I've tested the code and it works as intended.

Format data in csv parsed from xml using php

Following is the code, i am trying to format the data extracted from the xml file into csv.By default its inserted row wise. I am trying to make it presentable and easy to interpret.
I am not a professional coder so please excuse me if my solution is not an optimised one.
<?php
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="DynaMedResult.csv"');
//Using esearch utility capture WebEnv variable
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=DynaMed&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context); //Reads entire file into a string
$xml = simplexml_load_string($xml);
foreach ($xml->WebEnv as $WebenvSearch){
$WebEnv=$WebenvSearch;
}
//Using efetch utility and passing WebEnv variable parse the xml
$url= "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&term=DynaMed&WebEnv=$WebEnv&query_key=1&usehistory=y&retmode=xml";
$xml = file_get_contents($url, false, $context);
$xml = simplexml_load_string($xml); //Interprets a string of XML into an object
$fp = fopen('php://output', 'w');
foreach ($xml as $pubmedst){
$article=$pubmedst->MedlineCitation->Article->ArticleTitle;
$pmid=$pubmedst->MedlineCitation->PMID;
$journal1=$pubmedst->MedlineCitation->MedlineJournalInfo->MedlineTA;
$journal2=$pubmedst->MedlineCitation->MedlineJournalInfo->NlmUniqueID;
$pubyear=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Year;
$pubmonth=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Month;
$pubday=$pubmedst->MedlineCitation->Article->Journal->JournalIssue->PubDate->Day;
$authorl=$pubmedst->MedlineCitation->Article->AuthorList->Author->LastName;
$authorf=$pubmedst->MedlineCitation->Article->AuthorList->Author->ForeName;
$authori=$pubmedst->MedlineCitation->Article->AuthorList->Author->Initials;
$val1 = explode("\n", $article);
fputcsv($fp, $val1); //Format line as CSV and write to file pointer
$val2 = explode("\n", $pmid); //Splits a string by string in our case a newline
fputcsv($fp, $val2);
$val3 = explode("\n", $journal1.=$journal2);
fputcsv($fp, $val3);
$val4 = explode("\n", $authorl.=$authorf);
fputcsv($fp, $val4);
$val5 = explode("\n", $pubyear.=$pubmonth);
fputcsv($fp, $val5);
}
fclose($fp);
?>
As per the fputcsv() documentation, fputcsv() expects to be given an ARRAY of data to be output as csv data. You're passing in individual strings, so each string becomes a single "field" in a 1-column CSV file.
You need to build an array of data, then output the array:
$data[0] = 'foo';
$data[1] = 'bar';
$data[2] = 'baz';
fputcsv($fp, $data);
will produce
foo,bar,baz

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);

Categories