I have csv file like this:
data,IF,VVS1,VVS2
D,23,17,15
E,17,15,14
What i need is to convert this CSV into JSON but to look like this:
{"D" : {"IF":"23", "VVS1":"17", "VVS2":"15"},"E" : {"IF":"17", "VVS1":"15", "VVS2":"14"}}
Any help?
/* Lets suppose, the csv file is, mydata.scv */
<?php
$mydata = array();
if($file = fopen("mydata.csv","r")){
$csvheaders = fgetcsv($file);
while(($row = fgetcsv($file)) !== FALSE){
$arr = array();
for($i=1; $i<count($csvheaders); $i++){
$arr[$csvheaders[$i]] = $row[$i];
}
$mydata[$row[0]] = $arr;
}
fclose($file);
// encode $mydata array into json to get result in the required format
$mydatainformat = json_encode($mydata);
echo $mydatainformat; // This is your output.
}
?>
Maybe help you, but I recommend add error handling.
<?php
$file = fopen('test.csv', 'r');
$header = fgetcsv($file);
array_shift($header);
$data = array();
while ($row = fgetcsv($file))
{
$key = array_shift($row);
$data[$key] = array_combine($header, $row);
}
echo json_encode($data);
fclose($file);
Related
I have some problem when I convert an PHP array to Json. for more contex this is the code:
`<?php
$Users = array();
$file = fopen('usersFile.csv', 'r');
$row = fgets($file);
$ColumnKeys = explode(',', $row);
while (!feof($file)) {
$row = fgets($file);
$userData = explode(',', $row);
for ($i=0; $i<sizeof($columnkeys); $i++) {
$user[$columnKeys[$i]] = $userData[$i];
}
array_push($Users, $user);
}
fclose($file);
echo json_encode($Users);
?>`
The csv file containing the user data is this:
id,name,docNumber,dateBirth
1,Mario Mario,1694370,06/11/1953
2,Pau Pep,1725614,24/04/1964
The output look like this:
[{"id":"1","name":"Mario Mario","docNumber":"1694370","dateBirth\r\n":"06\11\1953\r\n"}, {"id":"2","name":"Pau Pep","docNumber":"1725614","dateBirth\r\n":"24\04\1964\r\n"}]
I don't know why in the output the $Users array contain Metacharacter in the dateBirth and their value. Is driving me mad.
it seems there is an option for json_encode called JSON_UNESCAPED_SLASHES
<?php
$Users = array();
$file = fopen('usersFile.csv', 'r');
$row = fgets($file);
$columnKeys = explode(',', trim($row));
while (!feof($file)) {
$row = fgets($file);
$userData = explode(',', trim($row));
for ($i=0; $i<sizeof($columnKeys); $i++) {
$user[$columnKeys[$i]] = $userData[$i];
}
array_push($Users, $user);
}
fclose($file);
echo json_encode($Users, JSON_UNESCAPED_SLASHES);
?>
Output:
[{"id":"1","name":"Mario Mario","docNumber":"1694370","dateBirth":"06/11/1953"},{"id":"2","name":"Pau Pep","docNumber":"1725614","dateBirth":"24/04/1964"}]
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));
I have a csv like this:
25/07/2016 3
25/07/2016 4
26/07/2016 4
26/07/2016 1
And the output that i expect, it have to be like this
25/07/2016 7
26/07/2016 5
I want to do this only using PHP.
I have to mention that i am not using mysql and i don't want to.
Is there a solution to do that?
Try something like this. This is just an edited version from this similar post.
$my_file = fopen('file.csv', 'rb');
$my_array = array();
while($row = fgetcsv($my_file)) {
$my_array[$row[0]] += $row[1];
}
"25/07/2016","3"
"25/07/2016","4"
"26/07/2016","4"
"26/07/2016","1"
For e.g. Let's say you have CSV file that contains data as above.
$arr = array();
$handle = fopen("example.csv", "r");
while(!feof($handle))
{
$arrOfCSVLine = fgetcsv($handle);
$date = $arrOfCSVLine[0];
$no = $arrOfCSVLine[1];
if(!array_key_exists($data,$arr))
{
$arr[$date] = $no;
}
else
{
$arr[$date] += $no;
}
}
echo '<pre>';
print_r($arr);
check this code..
$finalOutput = array();
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if(isset($finalOutput[$line[0]])){
$finalOutput[$line[0]] = $line[1] + $finalOutput[$line[0]];
} else {
$finalOutput[$line[0]] = $line[1];
}
}
print_r($finalOutput);
Can someone show me how to easily format an array with values like this?
I have a CSV file with values like below:
27383,15.99
80448,19.99
132876,11.99
150438,120
This is the format I would like:
$array[0]['id'] = 27838
$array[0]['price'] = 15.99
$array[1]['id'] = 80448
$array[2]['price'] = 19.99
What I have now is:
$data = file_get_contents('id_and_price.csv');
$data = explode(',', $data);
print_r($data);
//foreach($data as $d) {
// echo $d;
//}
You can do this quite easily with fgetcsv():
$arr = array();
$header = array('id', 'price');
$file = fopen('id_and_price.csv', 'r');
while($item = fgetcsv($file))
{
$arr[] = array_combine($header, $item);
}
print_r($arr);
<?php
$f = fopen('filename', 'r');
$arr = array();
while ($l = fgetcsv($f)) {
$arr[] = array_combine(array('id', 'price'), $l);
}
var_dump($arr);
?>
you need to use php explode...
http://php.net/manual/en/function.explode.php
$csv = "piece1,piece2,piece3,piece4,piece5,piece6";
$array = explode(",", $csv);
echo $array[0]; // piece1
echo $array[1]; // piece2
So I have a CSV file that looks like this:
12345, Here is some text
20394, Here is some more text
How can I insert this into an array that looks like so
$text = "12345" => "Here is some text",
"20394" => "Here is some more text";
This is what I currently had to get a single numerical based value on a one tier CSV
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r";
$qid = array();
$qid = str_getcsv($csvData, $csvDelim);
} else {
die("Could not open CSV file.");
}
Thanks for the replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:
$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text
If I tried this on the example csv above, how would the array be structured?
You can use fgetcsv() to read a line from a file into an array. So something like this:
$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
$key = array_shift($line);
$a[$key] = $line;
}
fclose($f);
var_dump($a);
Assuming that the first row in the CSV file contains the column headers, this will create an associative array using those headers for each row's data:
$filepath = "./test.csv";
$file = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($file)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
print_r($data);
If you are reading a file I can recommend using something like fgetcsv()
This will read each line in the CSV into an array containing all the columns as values.
http://at2.php.net/fgetcsv
$csv_lines = explode('\n',$csv_text);
foreach($csv_lines as $line) {
$csv_array[] = explode(',',$line,1);
}
edit - based on code posted after original question:
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r"; // assume this is the line delim?
$csv_lines = explode($csvDelim,$csvData);
foreach($csv_lines as $line) {
$qid[] = explode(',',$line,1);
}
} else {
die("Could not open CSV file.");
}
With your new file with two columns, $qid should become an array with two values for each line.
$csvDelim = ",";
$qid = str_getcsv($csvData, $csvDelim);
$text[$qid[0]] = $qid[1];