I am struggled at this point.
I am using the script for inserting/updating website languages.
The main structure of the JSON file looks like this
{
"English": {
"shortcode": "EN"
}
}
Here is a sample of the code I am using to insert a language into my JSON file
$data['french'] = $_POST;
array_push($json, $data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
But when I insert a new record into my JSON file new key appends in my JSON file and it looks like this,
{
"English": {
"shortcode": "EN"
},
"0": {
"French": {
"shortcode": "FR"
}
}
}
So my question is how can I insert a new record but to not insert the key "0", "1"..
Thanks in advance.
You only have to make $json[key] = value
$json['French'] = $_POST;
If it does not exist it is added, otherwise it is updated
It seems the $_POST is an array.
So you are pushing an array onto the $json array
Try this:
$json = $json + $_POST;
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
Related
So I'm trying to figure out why I get a NULL value in my .json file after I try to write the array to it. It only happens with the 'array_push' line after creating a new file. If there is a .json file already there with a value in it, it'll write to it correctly. The only thing I could guess was the file is missing the '{' and '}' in it upon creation.
I've got a small work around so far, but not sure that this is the right way to do it. Can someone tell me if this is good or bad?
Just to clarify, the .json document only holds the vault of NULL, there are no array elements or anything in the file besides the word NULL.
//CHECK IF FILE EXISTS, ELSE CREATE IT
$log_filename = "./site_files/logs/error-404-log.json";
if(!file_exists($log_filename)) {
touch($log_filename);
//LINE BELOW IS MY WORK AROUND, I'M NOT SURE IF THIS IS THE RIGHT WAY
file_put_contents($log_filename, json_encode(json_decode("{}")));
echo "$log_filename was created. <br />";
}
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($log_array != "") { $log_array = json_decode($json_data, true); }
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
$log_filename = "error-404-log.json"; // establish the path/to/filename.json
if (file_exists($log_filename)) { // if path/to/filename.json exists
$json = file_get_contents($log_filename); // access PRETTY json string
echo "pre-existing data: <div><pre>$json</pre></div><br>"; // display json string
$array = json_decode($json, true); // decode to prepare for new data
}
// data always maintains the same structure: an array of 2-element arrays
$array[] = [
'current_date_stamp' => date('Y-m-d H:i:s'),
'current_page_trail' => "foo"
];
// create/update the file
$new_json = json_encode($array, JSON_PRETTY_PRINT); // re-encode updated array data
echo "new data: <div><pre>$new_json</pre></div>"; // display new json string
file_put_contents($log_filename, $new_json); // create or overwrite file
Your code is failing because you are comparing $log_array with an empty string, this condition will always pass because this array will never be an empty string. In the if statement you decode the contents of the file, when the file has no content this will be an empty string and it will return NULL, after this you write this NULL value to your file. If you check if $json_data is an empty string your code should work, I would also recommend doing it like this:
$log_array = array();
$new_data = array(
'current_date_stamp' => $current_date_stamp,
'current_page_trail' => $current_page_trail
);
$json_data = file_get_contents($log_filename);
if($json_data != "") {
$log_array = json_decode($json_data, true);
//WHEN CREATING A NEW FILE, ARRAY_PUSH GIVES ERROR
array_push($log_array, $new_data);
$json_data = json_encode($log_array, JSON_PRETTY_PRINT);
file_put_contents($log_filename, $json_data);
}
This is better since if the string is empty all other actions are irrelevant.
After thorough research I have not been able to find the solution of a simple problem of appending an object to my JSON.
{
"menu": {
"parentmenu1": {
},
"parentmenu1": {
"pm_name": "iceberg 98 ",
"pm_time": "icebeest-98"
}
},
"projectname": "project1",
"place": "gzb",
"firstlogo": "flogo",
"logo": "logo",
"colordirection": "TopLeft",
"color1": "color1",
"color2": "color2",
"fontcolor": "fontcolor"
}
And my PHP code looks like this
<?php
$parentmenu="Sixty";
$childmenu= "hell";
$grandchildmenu= "icebeest";
$parentmenu1="PUSH Approach-98";
$childmenu1= "iceberg 98 ";
$grandchildmenu1= "icebeest-98";
$data = file_get_contents('format.json');
$json_arr = json_decode($data, true);
//$json_arr['menu']=array($parentmenu2);
$parentarray = array('pm_name'=>$childmenu1, 'pm_time'=>$grandchildmenu1);
echo $parentarray['pm_name'];
$json_arr['menu']['parentmenu1'] = $parentarray;
//array_push($json_arr['menu'], $parentarray);
file_put_contents('results_new.json', json_encode($json_arr));
?>
The parentmenu1 gets removed as soon as I re-run the code.
But if I try adding the 2 arrays at once in same file, then it will add.
So please let me find out the way in which I can add data with key to the end of the structure. TIA
I have the following data from an api call:
$userId = 1234; and $accessToken = 6789;. I want to write this to a json file called users.json.
Following this I make another api call and receive the following data:
$userId = 5678; and $accessToken = 0123;.
I then want to add this to the json file so that it looks like this:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
},
]
My code for writing to the json file looks like this. The $userId and $accessToken are defined elsewhere and are returning the correct values:
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
print_r($tempArray); // this doesn;t show anything as the users.json file contains `null`
array_push($tempArray, $userId);
array_push($tempArray, $accessToken);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
Unfortunately this isn't working. When I view the json file it just contains null Can anyone see any error with my code?
Thanks Raul
Your code is wrong. Correct it to look like this
<?php
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
if(empty($tempArray)){
$tempArray = [];
}
$newData = [
"userId" => $userId,
"accessToken" => $accessToken
];
array_push($tempArray, $newData);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
This will definitely work.
You need to to json_decode($content, true); to obtain an array and not an object.
See http://php.net/manual/fr/function.json-decode.php
Also the array_push is not correctly called.
It should be : array_push($tempArray, ["userid"=>$userId,"accesstoken" => $accessToken]);
You have error in json file so that all suggesion not working remove , at end of array. Then try below code :
Your json file should be:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
}
]
php :
$content = file_get_contents('user.json');
$tempArray = json_decode($content,true);
$new_array = array("userId"=>$userId,"accesstoken"=>$accessToken);
array_push($tempArray, $new_array);
$jsonData = json_encode($tempArray);
file_put_contents('user.json', $jsonData);
I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.
<?php
$handle = fopen("https://graph.facebook.com/search?q=sinanoezcan#hotmail.com&type=user&access_token=2227472222|2.mLWDqcUsekDYK_FQQXYnHw__.3600.1279803900-100001310000000|YxS1eGhjx2rpNYzzzzzzzLrfb5hMc.", "rb");
$json = stream_get_contents($handle);
fclose($handle);
echo $json;
$obj = json_decode($json);
print $obj->{'id'};
?>
Here is the JSON: {"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}
It echos the JSON but I was unable to print the id.
Also I tried:
<?php
$obj = json_decode($json);
$obj = $obj->{'data'};
print $obj->{'id'};
?>
Note that there is an array in the JSON.
{
"data": [ // <--
{
"name": "Sinan \u00d6zcan",
"id": "610914868"
}
] // <--
}
You could try $obj = $obj->{'data'}[0] to get the first element in that array.
data is an array, so it should be:
print $obj[0]->{'id'};
It looks like the key "data" is an array of objects, so this should work:
$obj = json_decode($json);
echo $obj->data[0]->name;
Have you tried $obj->data or $obj->id?
Update: Others have noted that it should be $obj->data[0]->id and so on.
PS You may not want to include your private Facebook access tokens on a public website like SO...
It's a bit more complicated than that, when you get an associative array out of it:
$json = json_decode('{"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}', true);
Then you may echo the id with:
var_dump($json['data'][0]['id']);
Without assoc, it has to be:
var_dump($json->data[0]->id);