writing all files in directory to json - php

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

Related

.JSON file creates NULL value via 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.

I'm writing json array to file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }]. Any Suggestions?

I'm writing json array to the file. I'm getting [{ , , }][{ , , }][{ , , }]. I need this output [{ , , },{ , , },{ , , }].
I'm not adding json items to the array, instead creating multiple arrays.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "a+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
//How to achieve this
[{"name":"ggg","qty":"ff","price":"ff"},
{"name":"ggg","qty":"ff","price":"ff"}]
I think you are write to the file after each post request and your array $a will only have the post array data.
that's why you getting your file at the end look like that
//output
[{"name":"ggg","qty":"ff","price":"ff"}]
[{"name":"ggg","qty":"ff","price":"ff"}]
so to fix this issue and get your data in the right format , each time you want to write to your file , first you need to load the data from the file and then merge it to your array $a and then write it again.
so this code should works in your case
//load file data
$data = file_get_contents("newfile.json");
$a = json_decode($data, true);
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
array_push($a,$new_data);
$json = json_encode($a);
$myfile = fopen("newfile.json", "w+") or die("Unable to open file!");
fwrite($myfile, $json);
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
I initialized $a with the data in file and change mode in fopen to w+
Try loading the data from the file into a, appending new_array to said data, then writing this new json list object into the file.
Managed to merge this together. There is most likely a better solution
array_merge in official PHP documentation
json_decode in official PHP documentation
$a = [{"name":"ggg","qty":"ff","price":"ff"}];
$b = [{"name":"ggg","qty":"ff","price":"ff"}];
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
or
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
use below code, hope it will meet your output:
$data = file_get_contents("newfile.json");
$a = explode("][", $data);
$x = '';
foreach($a as $y){
$x .= $y.",";
}
echo trim($x, ",");
There problem is with the appending data to newfile.json, Here a list already appended as a text, and after that whenever we append more text, it is appended as a text, not a json object, Therefore kindly try the following code along with your existing code:-
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// reading data from .json file
$data = file_get_contents('newfile.json');
// creating an array of object from the text of .json file
$tempArray = json_decode($data);
// adding our new object to array
array_push($tempArray, $new_data);
// creating json representation of the array
$jsonData = json_encode($tempArray);
// writing json representation to the .json file
file_put_contents('newfile.json', $jsonData);
Hope this will help.
$a = array();
$new_data = array(
'name' => $_POST["product_name"],
'age' => $_POST["quantity_stock"],
'city' => $_POST["item_price"]
);
// pushing the post data each time the page reloads with post values
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
$lastIndex = count($data);
$data[$lastIndex] = $new_data;
$myfile = fopen("newfile.json", "w") or die("Unable to open file!");\
fwrite($myfile, json_encode($data));
fclose($myfile);
$data = file_get_contents("newfile.json");
$data = json_decode($data, true);
print_r($data);

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

PHP writes null to JSON file

I've seen similar posts to this question but I can't seem to figure it out. I have a small PHP script that reads and writes form input to a JSON file, like this –
$file = 'data.json';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
Any ideas? Using PHP 5.5.9, checked that files are writeable. Both files have UTF8 encoding.
json_decode() will return NULL if the input is blank. Try this to ensure your $arr_data is an array...
$arr_data = json_decode($jsondata, true);
if ($arr_data === null) {
$arr_data = [];
}
maybe you want this code
<?php
$file = 'data.json';
$email='your mail info';
$arr_data = array();
$formdata = array(
'name' => strip_tags( trim($_POST['formName']) ),
'email' => $email,
'phone' => strip_tags( trim($_POST['formPhone']) ),
'message' => strip_tags( trim($_POST['formMessage']) )
// also tested this just using reg strings
);
$jsondata = file_get_contents($file);
//var_dump($jsondata); returns whatever string content is in the file, so seems to work
$arr_data = json_decode($jsondata, true);
// I added for if data.json is null to empty array
$arr_data = is_null($arr_data)?array():$arr_data;
array_push($arr_data, $formdata);
//var_dump($arr_data); returns NULL, not sure what happens here
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file, $jsondata);
?>
others
you should change your code to keep post data not null or default values and pay attention to file_get_contents method about file length

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