CREATE TABLE Posts
{
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
url VARCHAR(200)
}
json.php code
<?php
$sql=mysql_query("select * from Posts limit 20");
echo '{"posts": [';
while($row=mysql_fetch_array($sql))
{
$title=$row['title'];
$url=$row['url'];
echo '
{
"title":"'.$title.'",
"url":"'.$url.'"
},';
}
echo ']}';
?>
I have to generate results.json file.
To generate JSON in PHP, you need only one function, json_encode().
When working with database, you need to get all the rows into array first. Here is a sample code for mysqli
$sql="select * from Posts limit 20";
$result = $db->query($sql);
$posts = $result->fetch_all(MYSQLI_ASSOC);
then you can either use this array directly or make it part of another array:
echo json_encode($posts);
// or
$response = json_encode([
'posts' => $posts,
]);
if you need to save it in a file then just use file_put_contents()
file_put_contents('myfile.json', json_encode($posts));
Use this:
$json_data = json_encode($posts);
file_put_contents('myfile.json', $json_data);
You can create the myfile.json before you run the script.But its not compulsory if you have full sudo privileges(read/write permissions(For of you on Mac).
Here is a working Example:
<?php
// data stored in an array called posts
$posts = Array (
"0" => Array (
"id" => "01",
"title" => "Hello",
),
"1" => Array (
"id" => "02",
"title" => "Yoyo",
),
"2" => Array (
"id" => "03",
"title" => "I like Apples",
)
);
// encode array to json
$json = json_encode($posts);
$bytes = file_put_contents("myfile.json", $json); //generate json file
echo "Here is the myfile data $bytes.";
?>
Insert your fetched values into an array instead of echoing.
Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.
If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.
my_json.php
$array = array(
'title' => $title,
'url' => $url
);
echo json_encode($array);
Then in your script set the path to the file my_json.php
Here i have mentioned the simple syntex for create json file and print the array value inside the json file in pretty manner.
$array = array('name' => $name,'id' => $id,'url' => $url);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($array, JSON_PRETTY_PRINT)); // here it will print the array pretty
fclose($fp);
Hope it will works for you....
You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.
First, you need to decode it :
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
copy
Use PHP's json methods to create the json then write it to a file with fwrite.
Related
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);
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 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);
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));
I'm trying to write to a json file, and want to be able to overwrite an object if certain fields match. Right now, I have code that gets whats currently in the JSON file, but that just adds the latest object to the end of it. What I need to do is that if the message fields match, then I need to replace the entry with the newer one. Know what I mean?
Thanks for the help!
PHP:
$file = file_get_contents('test.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it);
//save the file
file_put_contents('test.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
You can use array_filter to find the element with the matching name and update it in place. This will not remove any existing duplicates for you, though.
$datum = array_filter($data, function (&$elem) use ($name, $lat, $lon, $it) {
if ($elem['message'] === $name) {
$elem = array('message' => $name /* snip */)
return true;
}
});
if (!$datum) { /* append array */ }
assuming I understand correctly, you only need to check if two elements in your $data array are equal, based on the message. Easiest way to do that is use the key of the data array, and reset it afterwards. so something similar to :
$file = file_get_contents('test.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[$message] = array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it);
//save the file
$data = array_values($data);
file_put_contents('test.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
this will increase memory consumption, so you can use md5() for the keys instead to keep it low.
If you use json_decode($string, true), you will get either an associative or numeric array. This array can be manipulated with standard php array methods.
$array = json_decode($string, true);
if(md5($data['message']) != md5($newMessage)) {
$array['message'] = $newMessage;
}
I used an md5, because i don't know how the message is structured.