Export Json Array to CSV in php - php

I have this array of provider
[
{
"reference":"01042",
"images": [
"http:\/\/static1.provider.com\/34\/01042.jpg"
]
},
{
"reference":"01057",
"images":[
"http:\/\/static1.provider.com\/57\/01057.jpg",
"http:\/\/static3.provider.com\/58\/01057.jpg",
"http:\/\/static2.provider.com\/59\/01057.jpg"]
},
...
]
I export with the following code
$json_file2 = file_get_contents('http://direct.provider.com/public/ref_urlimage_20.json', false);
$decoded = json_decode($json_file2);
$fp = fopen('imagenes.csv', 'w');
foreach($decoded as $comment) {
fputcsv($fp, $comment);
}
fclose($fp);
but it shows me the following result
01104,Array
01119,Array
40460,Array
00311,Array
00312,Array
00307,Array
When you need to export to this format
01104,http://static3.provider.com/155/01119.jpg
01119,http://static3.provider.com/155/04519.jpg,http://static3.provider.com/155/01148.jpg,http://static3.provider.com/155/0859.jpg
40460,http://static3.provider.com/155/01119.jpg,http://static3.provider.com/155/01118.jpg
00351,http://static3.provider.com/175/07219.jpg
...
Where am I doing wrong?
Thanks

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('output.csv', 'w');
$firstLineKeys = false;
foreach ($array as $line)
{
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
$line_array = array($line['reference']);
foreach ($line['images'] as $value)
{
$line_array.push($value);
}
fputcsv($f, $line_array);
}
Since You have array inside looping like the above code might help solve the issue
Try the below code this will work
<?php
//if (empty($argv[1])) die("The json file name or URL is missed\n");
//$jsonFilename = $argv[1];
//
//$json = file_get_contents($jsonFilename);
$json_file2 = file_get_contents('http://direct.funidelia.es/public/ref_urlimage_20.json', false);
error_reporting(E_ALL);
//echo $json_file2;die;
$json='{"data":'.$json_file2.'}';
//echo $json;
$array = json_decode($json, true);
//echo "<pre>";
//print_r($array);
//die;
$f = fopen('output.csv', 'w');
$firstLineKeys = false;
foreach ($array["data"] as $line)
{
// echo "<pre>";
// print_r($line);
// die;
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);
}
$line_array = array($line['reference']);
foreach ($line['images'] as $value)
{
array_push($line_array,$value);
}
fputcsv($f, $line_array);
}
echo "Success";
?>

Related

Problem in writing data to CSV file using PHP

I have a problem on writing the data to a csv file using php. It doesn't show any error, but it didn't create the file. Can anyone help me with this?
<?php
$mdarray = array();
$filename = basename(__FILE__, ".php");
$f = fopen("FILES/MonitorStatus.csv", "r");
while (($line = fgetcsv($f)) !== false) {
array_push($mdarray, $line);
}
fclose($f);
foreach ($mdarray as $key => $row) {
$Status[$key] = $row[3];
}
array_multisort($Status, SORT_ASC, $mdarray);
foreach ($mdarray as $line) {
$fp = fopen('file.csv', 'wb');
foreach ($line as $cell) {
fputcsv($fp, $cell);
}
fclose($fp);
}
?>

How to modify json to validate it?

I am downloading some json and merging them, but while doing that it creates a string like below,
}
][
{
I'd like to replace that with a comma in order to have a valid json
I tried something like this but it's not working:
$datas = array();
$json = str_replace("][",",", $datas);
$json = json_encode($json, JSON_PRETTY_PRINT);
print_r($json);
If I can manage to do that I'd use the same to replace columns name (I'm actually building this json from a csv) if possible.
UPDATE
To clarify I have multiple csv(s) from which I am then building a single json
FULL CODE
header('Content-Type: application/json');
$arr = array("04-12-2020",
"04-13-2020",
"04-14-2020",
"04-15-2020",
"04-16-2020",
"04-17-2020",
"04-18-2020",
"04-19-2020",
"04-20-2020",
"04-21-2020",
"04-22-2020",
"04-23-2020",
"04-24-2020",
"04-25-2020",
"04-26-2020",
"04-27-2020",
"04-28-2020",
"04-29-2020",
"04-30-2020",
"05-01-2020",
"05-02-2020",
"05-03-2020",
"05-04-2020",
"05-05-2020",
"05-06-2020",
"05-07-2020",
"05-08-2020",
"05-09-2020",
);
foreach($arr as $date) {
$url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports_us/".$date.".csv";
if (($handle = fopen($url, "r")) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
$json = json_encode($datas, JSON_PRETTY_PRINT);
fclose($handle);
print_r($json);
}
}
Don't call json_encode() inside the loop. Initialize $datas outside the loop, and encode it after the loop.
$datas = [];
foreach($arr as $date) {
$url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports_us/".$date.".csv";
if (($handle = fopen($url, "r")) !== FALSE) {
$csvs = [];
while($row = fgetcsv($handle)) {
$csvs[] = $row;
}
$column_names = [];
// Use header line to get array keys
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
array_shift($csvs); // remove header line
foreach ($csvs as $key => $csv) {
$new_data = [];
foreach ($column_names as $column_key => $column_name) {
$new_data[$column_name] = $csv[$column_key];
}
$datas[] = $new_data;
}
fclose($handle);
}
}
$json = json_encode($datas, JSON_PRETTY_PRINT);
print_r($json);

Convert json to csv using php

Hello i have small problem with converting json to csv.
Here is my code:
$jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}';
//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);
//Give our CSV file a name.
$csvFileName = 'file.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);
?>
I have tried with another json format like this [{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}] and its working perfect.
How to modify my code to save it correctly in csv format.
Pictures:
Now it save it like this:
I need to save it like this:
Can someone help me ?
Hope this will work..
<?php
$jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}';
$jsonDecoded = json_decode($jsonString, true);
$csvHeader=array();
$csvData=array();
jsontocsv($jsonDecoded);
print_r($csvHeader);
print_r($csvData);
$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
fputcsv($fp, $csvHeader);
fputcsv($fp, $csvData);
fclose($fp);
function jsontocsv($data)
{
global $csvData,$csvHeader;
foreach($data as $key => $value)
{
if(!is_array($value))
{
$csvData[]=$value;
$csvHeader[]=$key;
}
else
{
jsontocsv($value);
}
}
}
Json 2
<?php
$jsonString =file_get_contents("http://samples.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=b1b15e88fa797225412429c1c50c122a1");;
$jsonDecoded = json_decode($jsonString, true);
$csvHeader=array();
$csvData=array();
$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
$counter=0;
foreach($jsonDecoded["list"] as $key => $value)
{
jsontocsv($value);
if($counter==0)
{
fputcsv($fp, $csvHeader);
$counter++;
}
fputcsv($fp, $csvData);
$csvData=array();
}
fclose($fp);
function jsontocsv($data)
{
global $csvData,$csvHeader;
foreach($data as $key => $value)
{
if(!is_array($value))
{
$csvData[]=$value;
$csvHeader[]=$key;
}
else
{
jsontocsv($value);
}
}
}
try this:
$rowNr = 0;
$prevKey = "";
$target = [];
$iterator = new RecursiveArrayIterator($jsonDecoded['list'][$rowNr]);
iterator_apply($iterator, 'traverseStructure', array($iterator,$prevKey,&$target));
function traverseStructure($iterator, $prevKey, &$target) {
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
$prevKey = $iterator->key();
traverseStructure($iterator -> getChildren(), $prevKey, $target);
}
else {
if(isset($prevKey) && !is_int($prevKey)){
$row1 = $prevKey."/".$iterator->key();
}else{
$row1 = $iterator->key();
}
$row2 = $iterator->current();
$target[$row1] = $row2;
}
$iterator -> next();
}
}
fputcsv($fp, array_keys($target));
fputcsv($fp, array_values($target));

Read CSV File and Store Data In XML File

Hello i have This code
<?php
error_reporting(0);
function csv_to_array($filename='', $delimiter=';')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$csvFile = "example.csv";
$csv = csv_to_array($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
$xml = new DOMDocument("1.0");
$root = $xml->createElement("CATEGORY");
$domAttribute = $xml->createAttribute('name');
// Value for the created attribute
$domAttribute->value = 'Clear Skin 100ml Massage Oil 100ml-massage-oils';
// Don't forget to append it to the element
$root->appendChild($domAttribute);
$xml->appendChild($root);
foreach ($csv as $key => $value) {
$book = $xml->createElement("PRODUCT");
foreach ($value as $key => $value) {
echo $key. " ==> " . $value."<br>";
$key = $xml->createElement($key);
$value = $xml->createTextNode($value);
$key->appendChild($value);
$book->appendChild($key);
}
$root->appendChild($book);
}
$xml->formatOutput = true;
echo "<xmp>". $xml->saveXML() ."</xmp>";
$xml->save("final.xml") or die("Error");
I have created this script to fetch data from csv file and store in xml file . but i am haveing wrong output
my output :
Category ==> SMALL HOME APPLIANCES
Market ==> Breakfast
Segment ==> Hot beverage systems
PIXpro SKU ==> 19392107
it's not printing all the data from csv file but when i deleting
$key = $xml->createElement($key);
$value = $xml->createTextNode($value);
$key->appendChild($value);
$book->appendChild($key);
this code then i am getting all data echo just fine can any help me

Convert csv in php and get unique value

I would like to convert a csv file that has duplicate contents and i would like to sum the quantity and extract the price without sum it.
file.csv :
code,qty,price
001,2,199
001,1,199
002,2,159
002,2,159
Actual php that sum the quantiy and get a result with unique value and total qty.
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if (isset($newData[$row[0]])) {
$newData[$row[0]]+= $row[1];
} else {
$newData[$row[0]] = $row[1];
}
}
}
foreach ($newData as $key => $value) {
fputcsv($file, array($key, $value), ',', '"');
}
fclose($file);
?>
the result for this is:
code,qty
001,3
002,4
and i would like to add price, but without sum it.
The result i need is:
code,qty,price
001,3,199
002,4,159
I haven't tested this yet, but I think this is what you are looking for:
<?php
$tsvFile = new SplFileObject('file.csv');
$tsvFile->setFlags(SplFileObject::READ_CSV);
$tsvFile->setCsvControl("\t");
$file = fopen('file.csv', 'w');
$header = array('sku', 'qty');
fputcsv($file, $header, ',', '"');
foreach ($tsvFile as $line => $row) {
if ($line > 0) {
if(!isset($newData[$row[0]])) {
$newData[$row[0]] = array('qty'=>0, 'price'=>$row[2]);
}
$newData[$row[0]]['qty'] += $row[1];
}
}
foreach ($newData as $key => $arr) {
fputcsv($file, array($key, $arr['qty'], $arr['price']), ',', '"');
}
fclose($file);
?>
To start with, there's a nice function on the PHP page str_getcsv which will help you end up with a more legible array to work with:
function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
This is purely for legibility sake but now comes the code which would allow you to work over the array.
$aryInput = csv_to_array('file.csv', ',');
$aryTemp = array();
foreach($aryInput as $aryRow) {
if(isset($aryTemp[$aryRow['code'])) {
$aryTemp[$aryRow['code']['qty'] += $aryRow['qty'];
} else {
$aryTemp[$aryRow['code']] = $aryRow;
}
}
In the above code, it simply:
Loops through the input
Checks whether the key exists in a temporary array
If it does, it just adds the new quantity
If it doesn't, it adds the entire row
Now you can write out your expectant csv file :)

Categories