Converting array in Json PHP output not as expected - php

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"}]

Related

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

Append brackets at the end in the CSV file

At the beginning and at ending of the contents I have to append the brackets my csv file looks like this
date1,success,failure,count
1427653800,95,65,160
1427653800,30,10,40
1427740200,10,8,18
1427740200,30,38,68
1427826600,38,20,58
1427826600,60,10,70
1427653800,15,15,30
1427653800,10,10,20
After adding brackets the contents should look like this: [1427653800,95,65,160]
My php code is below:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, $row);
}
fclose($fp);
?>
this is my conn.php file ,please suggest me on this
it is better to use this query
$sql = "SELECT CONCAT('[','',(SUBSTRING(UNIX_TIMESTAMP(date1),1,10))),success,failure,CONCAT(count,'',']') from h_statistics";
it give you result like [1427653800,95,65,160] so no need to do any code in you while loop
Try to append and prepend the brackets :
$row[0] = '['.$row[0];
$row[3] .= ']';
fputcsv($fp, $row);
try with my function which is adding your text to the first and last element of the associative array:
<?php
function array_brackets($array,$prefix,$suffix){
//add prefix to the first element
end($array);
$key = key($array);
$array[$key] = $prefix . $array[$key];
//add sufix to the last element
reset($array);
$key = key($array);
$array[$key] = $array[$key] . $suffix;
return $array;
}
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
$fp = fopen("data.csv", "w");
fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
fputcsv($fp, array_brackets($row,"[","]"));
}
fclose($fp);
?>
Please run this code and give me the output:
<?php
$list = array ('date1', 'success', 'failure','count');
$sql = "SELECT (SUBSTRING(UNIX_TIMESTAMP(date1),1,10)),success,failure,count from h_statistics;";
$users_profile_user_id = mysqli_query($conn, $sql);
//$fp = fopen("data.csv", "w");
//fputcsv($fp, $list);
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC))
{
//fputcsv($fp, array_brackets($row,"[","]"));
print_r($row);
exit;
}
//fclose($fp);
?>

php to convert CSV to JSON with nested objects

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

echoing foreach loop

i have the following code
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
foreach ($contents as $key => $itemline)
{
}
foreach ($fnamearray as $key2 => $fname)
{
echo ($fname);
echo ($itemline);
}
what i want to do is to have the first line of each file echo so the output looks like
fname[0},itemline[0],fname[1],itemline[1]
what i am getting with the following is just this
fname[0],fname[1],fname[2].... ect
h
Assuming the indexes will always match:
$contents = file_get_contents('folder/itemtitle.txt');
$fnamedata = file_get_contents('/home/b1396hos/public_html/ofwgkta.co.uk/dd_folder/fname.txt');
$fnamearray = explode("\n", $fnamedata);
$contents = explode("\n", $contents);
for($i = 0; $i < count($contents); $i++)
{
echo $fnamearray[$i];
echo $contents[$i];
}
Since both arrays are simple, consecutive numeric indexed arrays, you can just use a for loop:
$l = max(count($fnamedata),count($contents));
for($i=0; $i<$l; $i++) {
$itemline = $contents[$i];
$fname = $fnamearray[$i];
// do stuff
}

How to Format CSV to ARRAY?

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

Categories