PHP read file (array) as array - php

How can I read a json array and add/merge a new element to it?
The content of my file data.json looks like this array:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
new element array example:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
I used explode() and file() but it failed (delimiter for index 1..)..
has someone another idea or it is the right way to solve?

Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().
After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.
Then you may append a new item to that array using [] suffix eg. $a[] = $b;
These three steps are exemplified below.
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);

<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode

Related

how to add another object with value in array

How to add another object with value in data?
Something start like :
$data=[{name:"apple"}]
And i wanted output like this
$data=[{name:"apple",city:"gotham"}]
Dont try and build JSON manually, create a PHP data structure that you want and then use json_encode() to make it into a JSON String
$d = [(object)['name' => 'apple', 'city' => 'gotham']];
echo json_encode($d);
RESULT
[{"name":"apple","city":"gotham"}]
If some values already exists, you should decode it to a PHP data struture and then add to it and convert back to JSON String
$data='[{"name":"apple"}]';
$d = json_decode($data);
$d[0]->city = 'Gotham';
$data = json_encode($d);
RESULT
[{"name":"apple","city":"Gotham"}]

How to fetch saved array from a file & access it like an array

I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.

Add object to JSON array with PHP [duplicate]

This question already has answers here:
Append data to JSON array using PHP
(3 answers)
Closed 4 months ago.
I am trying to call array_push to add data sent via a GET request to my json array that holds registration ids for my GCM Clients
<?php
//read current regids
$myfile = fopen("regids.json", "r") or die("Unable to open file!");
$current_regids = fread($myfile,filesize("regids.json"));
// decode json
$decoded_json= json_decode($current_regids);
//save to php format array
$array = array($decoded_json);
//close file
fclose($myfile);
//get registration id
$regid = $_GET["regid"];
//push new reg id into array
array_push($array,$regid);
echo json_encode($array);
?>
The JSON should be as follows
["regid1","regid2", "regid3","regid4"]
However when I run the code it inorder to array_push "regid5" it gives me this
[["regid1","regid2","regid3","regid4"],"regid5"]
Its a major headache
You already get an array when you decode it:
// decode json
$decoded_json= json_decode($current_regids);
// now you have an array or object, depending on the input
// in your case it seems to be an array
And then you put the result in another array:
//save to php format array
$array = array($decoded_json);
So now you have a nested array.
You need to remove this line / use $decoded_json as the array you want to manipulate:
$array = array($decoded_json);
Note:- If you use array_push() to add one element to the array it's better to use $array[] = "value" because in that way there is no overhead of calling a function and it is also much faster and safer than array_push().

unable to decode json variable

I have following piece of code which is generating JSON variable. I use php built in json_decode function to decode the json variable but i am getting NULL after decoding JSOn variable.
$a=array("targetAction"=>"getHeadFields","targetHead"=>$table_name);
$obj1 = Post_Uamsdata($a);
echo $obj1;
$file = json_decode($obj1,true);
var_dump($file);
$obj1 is my json variable. whenever i echo it i get the result as follows:
{"success":"yes","error":"","message":"","arguments":"[{\"fieldNo\":\"1\",\"fieldName\":\"ItemType\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"2\",\"fieldName\":\"Long\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"3\",\"fieldName\":\"Lat\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"4\",\"fieldName\":\"MapDate\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"5\",\"fieldName\":\"FieldNote\",\"fieldType\":\"character(64)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]}]"}
i have checked it in online json validator and it is saying that this JSOn is valid. But whenever i decode this $obj1 into $file then i am always getting NULL.
after json_decode we get the following, But I guess this is not what you want. You want the fieldNo, fieldName etc also to be parsed.
$json = '{"success":"yes","error":"","message":"","arguments":"[{\"fieldNo\":\"1\",\"fieldName\":\"ItemType\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"2\",\"fieldName\":\"Long\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"3\",\"fieldName\":\"Lat\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"4\",\"fieldName\":\"MapDate\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"5\",\"fieldName\":\"FieldNote\",\"fieldType\":\"character(64)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]}]"}';
$arr = json_decode($json, true);
echo "<pre>";
print_r($arr);
Output is as follows
Array
(
[success] => yes
[error] =>
[message] =>
[arguments] => [{"fieldNo":"1","fieldName":"ItemType","fieldType":"character(16)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"2","fieldName":"Long","fieldType":"character(20)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"3","fieldName":"Lat","fieldType":"character(20)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"4","fieldName":"MapDate","fieldType":"character(16)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"5","fieldName":"FieldNote","fieldType":"character(64)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]}]
)
As http://php.net/manual/en/function.json-decode.php indicates that the function will only work for UTF-8 encoded string, try the following:
$file = json_decode(mb_convert_encoding($obj1, 'UTF-8'),true);

Json to Array to XML[Php]

I'm trying to convert an array to xml using a json in php
The json and array work fine but when I try converting the array to xml I keep getting an error.
Call to undefined function array_to_xml()
This is the json
{"host":"127.0.0.1","username":"root","password":"something","dbname":"something","table":"something"}
Json to `array
$json = json_decode(file_get_contents('something.json'), true);
$info = array(
$json['host'],
$json['username'],
$json['password'],
$json['dbname'],
);
Array to xml
simplexml_load_string(array_to_xml($json, new SimpleXMLElement('<connection/>'))->asXML()) or die("can't read");
Maybe because there is no function called array_to_xml()? You have to define it first.

Categories