Convert JSON array to CSV using PHP - php

i need to have the csv have the format of the first picture but im currently getting the second picture as a final result, how can i set it properly so MailChimp can read the csv properly
$jsonDecoded = json_decode(file_get_contents('emails.json', true), true);
$list = array(
array('Email Address', 'First Name')
);
$timestamp = time();
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
//if old file exist delete
$fp = fopen('emails.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Desired Output
Current Output with the above code

The main Issue I can see is you are overwriting the same field in the array, because you are using the same key in the loop
//$timestamp = time(); - only set once, won't change
foreach($jsonDecoded as $entry)
{
// this will update, but won't produce a different key for each iteration,
// because the loop might be faster than the smallest precision
// that the time() function can produce
$timestamp = time();
$new = array($entry['email'], $entry['name']);
$list[$timestamp] = $new;
}
I don't see a use for the timestamp itself, so I suggest just use array_push() or the shorthand shown below
foreach($jsonDecoded as $entry)
{
$new = array($entry['email'], $entry['name']);
$list[] = $new; // this just adds the element to the end of the array
}

Related

How to convert JSON data to CSV format on the fly with out using csv file

I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);

Taking a variable from foreach when each time it executes

I have following piece of code in foreach loop.
foreach($_FILES["upload"]["tmp_name"] as $key=>$tmp_name)
{
$guid = (int) get_input('guid');
$file = new FileCreate($guid);
$fileId = $file->guid;
}
What I want to execute is I want to take the value of $fileId every time when foreach executes and stores into a array variable , is it possible to do that ? Or else how we can keep the value of $fileID on first execution of foreach.
You can write something like this:
$myids = array();
foreach($_FILES["upload"]["tmp_name"] as $key=>$tmp_name) {
$guid = (int) get_input('guid');
$file = new FileCreate($guid);
$fileId = $file->guid;
array_push($myids, $fileId);
}
your question is wrong because $_FILES["upload"]["tmp_name"] is not an array and contains a text value. But if you want to have the first element of an array there is no need to do anything special, easily do like this:
foreach($arr as $key=>$val){
...
}
$first_item = $arr[0];
$first_item_id = $arr[0]->id;

How to read empty cells in PHPExcel?

This following code simply ignore all empty cells in my excelsheet.
Is there any way to read empty cell or replace them to "Null" values?
See the code here---https://arjunphp.com/how-to-use-phpexcel-with-codeigniter/
$file = './files/test.xlsx';
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
$maxCell = $objPHPExcel->getHighestRowAndColumn();
$newdata = array();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
I tried this following code
$newdata = $objPHPExcel->rangeToArray($cell . $maxCell['column'] . $maxCell['row']);
$newdata = array_map('array_filter', $data);
$newdata = array_filter($data);
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
//send the data in an array format
$data['header'] = $header;
$data['values'] = $arr_data;
print_r($newdata);
Get this error messgae... Fatal error: Call to undefined method PHPExcel::getHighestRowAndColumn()
you're try to wrong way, in this way you only get the last active cell value and if you try to get empty cell cell value in middle you're not able to get value. and you use some PhpSpreadsheet function and also some time you try get value using class object. check your code one more time.

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

how to put array data into text file using php

if i use the following code i got data in text file
{"title":"sankas","description":"sakars","code":"sanrs"}
{"title":"test","description":"test","code":"test"}
but my code is working on
{"title":"sankas","description":"sakars","code":"sanrs"}
so i could not add more rows.where i want to change to get correct results.
$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);
use php's file_put_content() more information here http://php.net/manual/en/function.file-put-contents.php
Update :
assuming that the data is correctly being passed. here is what you can do.
$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";
//using the FILE_APPEND flag to append the content.
file_put_contents ($file, $json, FILE_APPEND);
Update 2:
if you want to access the value back from the text file. overlay.txt here is what you can do
$content = file_get_contents($file);
if you want to fetch title, code, and description separately. and if the string is in json then you need to convert it into array first by using.
//this will convert the json data back to array
$data = json_decode($json);
and to access individual value you can do it like this if you have one row
echo $data['title'];
echo $data['code'];
echo $data['description'];
if you have multiple rows then you can use php foreach loop
foreach($data as $key => $value)
{
$key contains the key for example code, title and description
$value contains the value for the correspnding key
}
hope this helps you.
Update 3:
do it like this
$jsonObjects = file_get_contents('./videos/overlay.txt');
$jsonData = json_decode($jsonObjects);
foreach ($jsonData as $key => $value) {
echo $key . $value;
//$key contains the key (code, title, descriotion) and $value contains its corresponding value
}

Categories