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
Related
I am running an API, the response of this API is returning response in comma separated values.
I am returning response in $result.
Response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type 106864,new,"Gift Vouchers worth ₹2000 # for just ₹999","Get it for just ₹999",,"Gift Items","ABC Company",http://example1.com,http://example2.com,"2016-04-07 00:00:00","2016-05-01 00:00:00",sale
Below are the headers in response:
lmd_id,status,title,description,code,categories,store,url,link,start_date,expiry_date,coupon_type
Code I have tried:
function str_putcsv($result) {
# Generate CSV data from array
$fh = fopen('php://temp', 'rw'); # don't create a file, attempt
# to use memory instead
# write out the headers
fputcsv($fh, array_keys(current($result)));
# write out the data
foreach ( $result as $row ) {
fputcsv($fh, $row);
}
rewind($fh);
$csv = stream_get_contents($fh);
fclose($fh);
return $csv;
}
With the code above I am not able to find where this code is generating CSV.
Another code:
$fp = fopen('data.csv', 'w');
foreach($data as $line){
$val = explode(",",$line);
fputcsv($fp, $val);
}
fclose($fp);
Above code is generating file on FTP but there is no data in it. It is generating blank CSV.
I want to convert this response into CSV file and put it on a FTP or in the same directory.
You can just put everything in an array. And use int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
Example from php.net:
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('path/to/file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
read more about fgetcsv here
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.
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);
my data
this1
this2
this3
this4
what I want
$keepit[0]='this1';
$keepit[1]='this2';
$keepit[2]='this3';
$keepit[3]='this4';
data uri
data:text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=
Is it possible to do this?
You can do this with normal file methods using the data:// protocol:
$data = file('data://text/plain;charset=utf-8;base64,dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
Alternatively though you can pull out the base64 encoded string and decode it yourself:
$plaintext = base64_decode('dGhpczENCnRoaXMyDQp0aGlzMw0KdGhpczQ=');
If the encoded string can be decoded this will work:
$file_path = ''; // change this.
$fp = fopen($file_path, 'rb');
$contents = fread($handle, filesize($file_path));
fclose($fp);
$data_uri = preg_split('/,/', $contents);
$encoded = $data_uri[1];
$decoded = base64_decode($encoded);
var_dump($decoded);
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);