PHP writes null to JSON file - php

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

Related

Append non english chars to json file

I'm trying to append new item to json file which the fields value are hebrew.
This is my code and the result is that all file is converted to: "title":"\u05de\u05e1\u05d9...
Should i convert it? i want it to be readable
$additionalArray = array(
'id' => 1,
'title' => 'כותרת',
'author' => 'תוכן'
);
//open or read json data
$data_results = file_get_contents('../db/memory.json');
$tempArray = json_decode($data_results, true);
//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);
file_put_contents('../db/memory.json', $jsonData);
the second parameter to json_encode is an options bitmask. You can supply JSON_UNESCAPED_UNICODE to prevent PHP from escaping your strings.
$jsonData = json_encode($tempArray, JSON_UNESCAPED_UNICODE);

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

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

Sending JSON Array via PHP (Campaign Monitor)

I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}

Categories