PHP read and write JSON from file - php

I have the following JSON in a file list.txt:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
How do I add "bross":{"first":"Bob","last":"Ross"} to my file using PHP?
Here's what I have so far:
<?php
$user = "bross";
$first = "Bob";
$last = "Ross";
$file = "list.txt";
$json = json_decode(file_get_contents($file));
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
$json[$user] = array("first" => $first, "last" => $last);
I'm using PHP5.2. Any thoughts? Thanks!

The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.

The sample for reading and writing JSON in PHP:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));

Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).

You need to make the decode function return an array by passing in the true parameter.
json_decode(file_get_contents($file),true);

Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);

This should work for you to get the contents of list.txt file
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);

If you want to display the JSON data in well defined formate you can modify the code as:
file_put_contents($file, json_encode($json,TRUE));
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str1=utf8_encode($str);
$str1=json_decode($str1,true);
foreach($str1 as $key=>$value)
{
echo "key is: $key.\n";
echo "values are: \t";
foreach ($value as $k) {
echo " $k. \t";
# code...
}
echo "<br></br>";
echo "\n";
}

When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]

Related

How can I decode a JSON string in PHP?

I am trying to read a string into an array in PHP, but it doesn't work for me.
The string I would like to read:
$output = {"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}
The code I am using:
$arr = explode(',', $output);
foreach($arr as $v) {
$valarr = explode(':', $v);
preg_match_all('/"(.*?)"/', $valarr[0], $matches);
$narr[$matches[1][0]][$matches[1][1]] = $valarr[1];
}
Specifically, I would like to access the value for 'message' (i.e., 'Approved').
I tried this, but it still fails:
echo 'MESSAGE ' . $arr['message'];
Here is working code,
$arr = '{"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}';
$arr = json_decode($arr, true);
echo $arr['message'];
print_r($arr);
Here is working link
Thats not string, its json..
$array = json_decode($output,true);

How to get JSON response in to PHP variables

I am getting following response in JSON format and I want it to convert it into PHP variables.
JSON:
{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900"
,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}
output should be PHP:
$transkey = aa900d54-7bfb-47e9-a5de-e423ec34a900;
$vkey = fbb28b32-f439-4801-a434-99c70aa388ca
please advice me how to do it.
Just simply use json_decode();
$result= json_decode($jSon);
var_dump($result); // to see the output
json to array(json_decode) and then extract from array.
$arr = json_decode($json, true);
extract($arr);
var_dump($CreateTransactionResponse);
Output:
array (size=1)
'CreateTransactionResult' =>
array (size=3)
'TransportKey' => string 'aa900d54-7bfb-47e9-a5de-e423ec34a900' (length=36)
'ValidationKey' => string 'fbb28b32-f439-4801-a434-99c70aa388ca' (length=36)
'Messages' =>
array (size=0)
empty
More about extract
use $CreateTransactionResult['TransportKey'] to access Transport Key from JSON. Similarly $CreateTransactionResult['ValidationKey'] for Validation Key.
If you want to access your json try to decode it first:
$result = json_decode($yourJSON, true);
foreach($result['CreateTransactionResponse'] as $key => $val){
echo $transkey = 'TransportKey= ' . $val['TransportKey'] . '<br/>;
echo $vkey = 'ValidationKey= ' . $val['ValidationKey'];
}
Or if it is an array of JSON's
$result = json_decode($yourJSON, true);
$data = [];
foreach($result['CreateTransactionResponse'] as $key => $val){
$data[] = [
'TransportKey' => $val['TransportKey'],
'ValidationKey' => $val['ValidationKey']
];
}
print_r($data);
try this code it will work
$JSON='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900" ,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
$arr=json_decode($JSON, TRUE);
foreach ($arr as $value) {
foreach ($arr['CreateTransactionResponse'] as $key => $var) {
echo 'TransportKey = '.$var['TransportKey'].'<br>';
echo 'ValidationKey = '.$var['ValidationKey'].'<br>';
foreach ($var['Messages'] as $key => $msg) {
echo 'Messages = '.$msg.'<br>';
}
}
}
In this case,If its a single and TransportKey and a single ValidationKey value (not an array/object is passed) at a time, this is the simplest. Else if object contains objects or inside objects that we want to use or convert to variable, should use a foreach to loop through the object.
//Debuggig
//The string you provided is converted to a json object
//In your case if it is a json object already pass directly it to $j
//below is just for debugging and understanding
//$json='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900","ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
//$j=json_decode($json);
$transkey=$j->CreateTransactionResponse->CreateTransactionResult->TransportKey;
$vkey=$j->CreateTransactionResponse->CreateTransactionResult->ValidationKey;
echo $transkey."</br>";
echo $vkey."<br/>";
/*result as said:
aa900d54-7bfb-47e9-a5de-e423ec34a900
fbb28b32-f439-4801-a434-99c70aa388ca
*/

json_encode particular part of array

$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json
By this way I am reading all the data, but how can I read the data of
only Real or Inter?
For example, if it is json_decoded I can do so:
For Inter:
echo $array['Inter'];
For Real:
foreach($array["Real"] as $real){
echo $real."<br>";
}
How can I do the same with json_encode()?
json_encode() returns a string, so you can't access its parts without parsing the string. But you can do the following instead:
echo json_encode($array['Inter']);
As I understand your question you need to output the json`d object.
Input
$input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
In php:
// Second true is for array return, not object)
$string = json_decode($input, true)
echo $string['Inter'];
In Javascript (jQuery):
var obj = jQuery.parseJSON(input);
if (obj != undefined) {
echo obj['Inter'];
}
UPD:
If you need to get an json in all arrays you need to make follow:
$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
foreach($array as $key => $value) {
$array[$key] = json_encode($value);
}
After this code all variables in array will be json`ed and you can echo them in any time

Add new lines to JSON

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?
json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"
Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);

How to correctly return an array to ajax call in php?

ajax calls below php and expect an array of json to be return. I think I have the data ready but don't know how to return them correctly.
$files = array();
foreach($db2_databaselist as $db) {
$file = new stdClass();
$file->data = date('Y-m-d--H:i:s',strtotime($db));
$file->attr = new stdClass();
$file->attr->rel = "file";
$file->attr->timestamp = $db.$type[0];
$files[] = json_encode($file);
}
echo "<pre>Output = " . print_r($files,TRUE) . "</pre>";
echo "<BR><BR><BR>";
print_r($files, TRUE);
where print_r($files,TRUE) gives me
Output = Array
(
[0] => {"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}}
[1] => {"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}}
[2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
)
But print_r($files,TRUE) returns nothing.
How can I get php to return
[
{"data":"2011-08-07--02:30:05","attr":{"rel":"file","timestamp":"20110807023005w"}},
{"data":"2011-07-31--02:30:09","attr":{"rel":"file","timestamp":"20110731023009w"}},
[2] => {"data":"2011-07-24--02:30:09","attr":{"rel":"file","timestamp":"20110724023009w"}}
]
You don't need json encode after the loop as things are. You need implode. Your array values are already JSON strings, which means that using json_encode will only escape the strings!
Instead:
echo '['.implode(',',$files).']';
OR! You could skip json_encode on this line:
$files[] = json_encode($file);
And the end of the loop would look like this instead:
$files[] = $file;
}
$files = json_encode( $files );
you need to use json_encode php function
print json_encode($files);
echo json_encode($files) should be enough

Categories