.JSON file creates NULL value via PHP - php

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.

Related

Adding object to array also adds 'null'

I send the following data to my php file via ajax:
JSON.stringify({test1: '1', test2: '2'})
I would like to write this data to my JSON FILE content.json containing an empty array
[]
I only want to add the content though if it is not there, yet. This is my PHP code:
$jsonStringObject = file_get_contents("php://input");
$phpObject = json_decode($jsonStringObject);
$newJsonStringObject = json_encode($phpObject);
header('Content-Type: application/json');
$jsonString = file_get_contents('content.json');
$data = (array) json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
It almost works. Something is wrong with the way the data is added to the array because when I call the function for the first time, it updates content.json to
[null,{"test1":"1","test2":"2"}]
On calling the function again, it adds the object again despite the if-statement:
[null,{"test1":"1","test2":"2"},{"test1":"1","test2":"2"},{"test1":"1","test2":"2"}]
Can anyone help me to spot the mistake?
You're comparing apples and oranges (or rather objects to arrays).
Make sure you decode all json as arrays:
$jsonStringObject = file_get_contents("php://input");
// Added true as second argument to get it bas as an array
$phpObject = json_decode($jsonStringObject, true);
$jsonString = file_get_contents('content.json');
// Removed the (array) since the second argument literally means "return as array"
$data = json_decode($jsonString, true);
if (in_array($phpObject, $data) === false){
$data[] = $phpObject;
}
$newJsonString = json_encode($data);
file_put_contents('content.json', $newJsonString);
Demo: https://3v4l.org/rnCn5

How can I select the key to remove? PHP and JSON

I'm trying to select a dynamic method to remove key from a json file,at the moment, this code overwrite ALL json file and write {"0":{"name":null,"url":null}} do you know how can I solve it? I just want delete ONE key when I press delete button.
PHP:
<?php
var_dump($_POST);
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
$data[] = array(
'name' => $name,
'url' => $url
);
foreach($data as $key=>$val){
// check status
if ($val["status"]=="DELETE"){
// this deletes record from array
unset($data[$key]);
}
}
file_put_contents('js/json.json', json_encode($data, JSON_FORCE_OBJECT));
header('Location: http://URL/index.php');
?>
JSON:
[{"name":"asdf","url":"asdf"},{"name":"asfd","url":"dsaf"}]
You are reading the data into $data_array and writing out $data, so what you are writing is the data you want to delete - after you've processed it to delete all the records.
What this code does is take the $url value (from however it's set) and goes through the $data_array read from the input file and if it finds a match, it removes it. Then writes out $data_array back to the file.
$data_url = 'js/json.json';
$data_json = file_get_contents($data_url);
$data_array = json_decode($data_json, true);
// Next line just for testing
//$url = "asdf"; // $_POST['URL']; ?
foreach($data_array as $key=>$val){
// check URL
if ($url == $val["url"]){
// this deletes record from array
unset($data_array[$key]);
}
}
$data_array = array_values($data_array);
file_put_contents($data_url, json_encode($data_array));

How to decode value from json, php

I need to decode the below json from a mobile app
Array
(
[{"unm":"admin","pw”:”password”}] =>
)
and my php code is
$obj1 = print_r($_REQUEST, true); //get $_request variable data(responce of login) data as it is
foreach($obj1 as $key => $value)
{
$obj2 = $key; //get first key
}
$obj3 = json_decode($obj2); //decode json data to obj3
$mob_user_name = $obj2['unm']; //getting json username field value
$mob_user_password = $obj2['pw']; //getting json password field value
Hope this will fix your issue,
Note: content is nothing but which you have received from iOS app
content = Array (
[{"unm":"admin","pw”:”password”}] => )
parse that in php
$json = json_decode($content, true);
print json[0]['unm']; /* prints the username */
print json[0]['pw']; /* prints the password */
{"unm":"admin","pw”:”password”} is an object, and json_decode() will by default build it as so.
$obj = json_decode('{"unm":"admin","pw”:”password”}');
echo $obj->unm;
echo $obj->pw;
If for some reason you want it to be converted to an associative array, set the second parameter of json_decode() to true as specified in the manual.
$arr = json_decode('{"unm":"admin","pw”:”password”}', true);
echo $arr['unm'];
echo $arr['pw'];

writing all files in directory to json

I made simple text editor and now working on image upload and image manager. I have set up manager to read .json file with all images and it works ok. The problem is for php script to actually write newly added images to that json.
$file = "images.json";
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
$arr_data = array(
'link' => $image,
'tag' => 'images',
);
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$jsondata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));
I am getting
Warning: array_push() expects parameter 1 to be array
even tho array data is provided. How to solve this?
If you are starting with an empty file i.e. images.json then the first time you run these 2 lines
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
the second line will change $arr_data into a boolean probably. As json_decode() will fail to convert nothing into an array.
So add this to initialize the file for use
<?php
$file = "images.json";
file_put_contents($file, '[]'); // init the file
You are also reusing the $arr_data variable so amend this also and you are overwriting the new array as well
$file = "images.json";
file_put_contents($file, '[]'); // init the file
$arr_data = array();
foreach(glob('/uploads/*') as $image) {
// amended to not reuse $arr_data
// ameded to not overwrite the array as you build it
$new_arr[] = array( 'link' => $image, 'tag' => 'images');
}
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data,$new_arr);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata));

how to retrieve array value using php

I want to retrieve array value.
This is my array value:
overlay.txt:
{"title":"sss","description":"sss","code":"sss"}
{"title":"trtr","description":"trtr","code":"tyrytr"}
{"title":"ret54","description":"56tr","code":"ty76"}
{"title":"rgfdg","description":"dfgdfg","code":"dfgdfg"}
{"title":"asfafdsf","description":"sdfsdf","code":"sdfsdfsdf"}
This is my code: but this is not working.why?
How to retrieve value from overlay.txt file.
I did not get all title value.
I do not known how to get title value from overlay.txt
The $title is showing empty.
Where I want to change in my code to get $title value.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
$filecon = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays',$filecon);
//overlays page;
foreach($filecon as $files)
{
$title=$files['title'];
echo $title;
}
You're encoding your array to JSON, so at some point you need to decode it again into a PHP array. Since you actually have several JSON objects in the file, you need to decode each one individually. Assuming it's always one JSON object per line, this'll do:
$jsonObjects = file('overlay.txt', FILE_IGNORE_NEW_LINES);
foreach ($jsonObjects as $json) {
$array = json_decode($json, true);
echo $array['title'];
...
}
This will very quickly break if there are line breaks within the serialized JSON, e.g.:
{"title":"ret54","description":"foo
bar","code":"ty76"}
That way of storing the data is not very reliable.
make overlay.txt fully json format:
[
{"title":"sss","description":"sss","code":"sss"},
{"title":"trtr","description":"trtr","code":"tyrytr"},
...
]
and try this:
$raw = file_get_contents('./videos/overlay.txt', true);
$this->load->view('includes/overlays', array("filecon" => json_decode($raw)));
overlay page:
<?php
foreach($filecon as $files) {
echo $files['title'];
}
?>
If you want to use $filecon in view file,
set an array which has the key "filecon" in $this->load->view()'s second argument.
http://codeigniter.com/user_guide/general/views.html

Categories