Disclaimer: I am very unfamiliar with PHP. The answers I have seen floating around Stack don't seem applicable to my situation. This could be due to my unfamiliarity.
I need to write to an existing array in a JSON file:
[
[
// data should be written to this array
],
[]
]
My PHP looks like so:
<?php
$ip = $_POST["ip"];
$likes = "../data/likes.json";
$fp = fopen($likes, "a");
fwrite($fp, json_encode($ip) . ", ");
fclose($fp);
?>
When the PHP runs it writes to the end of the file like so (as you'd expect):
[
[
],
[]
]"data",
How do I resolve my PHP to do so?
Open the file:
$filename = '../data/likes.json'
$fp = fopen($filename, 'r');
Then read the existing data structure into a variable:
$data = json_decode(fread($fp, filesize($filename)));
Add the data to the correct array entry:
$data[0][] = $ip;
Close and reopen the file with write privileges, so that we overwrite its contents:
fclose($fp);
$fp = fopen($filename, 'w');
And write the new JSON:
fwrite($fp, json_encode($data));
$ip = $_POST["ip"];
$likes = json_decode(file_get_contents("../data/likes.json"), true);
$likes[] = $ip;
file_put_contents("../data/likes.json", json_encode($likes));
You can not fimply add record to file and get valid json jbject.
So idea of that code:
we read all from file, append array with new data, and rewrite file with new data
Related
I'm trying to write a json file with data gathered via get requests. The json file is a 2D array of strings, but when the data is written to the file, the nested array is written twice.
<?php
//used for parsing html
include("simple_html_dom.php");
//read the file
$fp = fopen("j.json", "r");
$t = fread($fp, filesize("j.json"));
fclose($fp);
$loaded = json_decode($t);
//print the loaded array
print_r($loaded);
//gathering the data
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo1 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$data = file_get_html($url)->find("span[class=ora] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo2 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
$url = "https://www.soldionline.it/quotazioni/dettaglio/IT0003934657.html";
$prezzo3 = file_get_html($url)->find("span[class=val] b", 0)->plaintext;
//adding the new data to the array
array_push($loaded, array($prezzo1, $prezzo2, $prezzo3, $data));
//the new json string is parsed and ready to be written
$s = json_encode($loaded);
//printing stuff to ensure the data is correct
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
//write the new json string to the same file
$fp = fopen("j.json", "w");
fwrite($fp, $s);
fclose($fp);
?>
j.json before the script runs:
[]
What the script prints:
Array ( )
[["128,54","128,54","128,54","30\/12"]], type=string
Array ( [0] => Array ( [0] => 128,54 [1] => 128,54 [2] => 128,54 [3] => 30/12 ) )
j.json after the script:
[["128,54","128,54","128,54","30\/12"],["128,54","128,54","128,54","30\/12"]]
I tried opening the file like this: $fp = fopen("j.json", "r+"); and at the and i changed the script:
$s = "\"".json_encode($loaded)."\"";
echo "<br>".$s.", type=".gettype($s)."<br>";
print_r($loaded);
fwrite($fp, $s);
fclose($fp);
And I found out that a null is being written too:
[]"[["128,54","128,54","128,54","30\/12"]]""null"
The browser sends two requests when visiting a url, a request to the php file and another request to /favicon.ico. The second request is send to check if the site has a favicon. This second requests causes the script to execute twice.
The request for the favicon can be prevented by following the steps described here: https://stackoverflow.com/a/38917888/6310593
I have this .json file:
[
{
"id": 1,
"title": "Ben\\'s First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\'s Second Blog Post",
"content": "This is the content"
}
]
This is my PHP code:
<?php
$data[] = $_POST['data'];
$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);
The thing is, I'm not exactly sure how to achieve it. I'm going to call this code above every time a form is submitted, so I need the ID to increment and to also keep the valid JSON structure with [ and {, is this possible?
$data[] = $_POST['data'];
$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.
// read the file if present
$handle = #fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
You're ruining your json data by blindly appending text to it. JSON is not a format that can be manipulated like this.
You'll have to load your json text, decode it, manipulate the resulting data structure, then re-encode/save it.
<?php
$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));
Let's say you've got [1,2,3] stored in your file. Your code could turn that into [1,2,3]4, which is syntactically wrong.
Sample code I used to append additional JSON array to JSON file.
$additionalArray = array(
'id' => $id,
'title' => $title,
'content' => $content
);
//open or read json data
$data_results = file_get_contents('results.json');
$tempArray = json_decode($data_results);
//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
If you want to add another array element to a JSON file as your example shows, open the file and seek to the end. If the file already has data, seek backwards one byte to overwrite the ] following the last entry, then write , plus the new data minus the initial [ of the new data. Otherwise, it's your first array element, so just write your array normally.
Sorry I don't know enough about PHP to post actual code, but I've done this in Obj-C and it's allowed me to avoid reading the whole file in first just to add onto the end:
NSArray *array = #[myDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
FILE *fp = fopen(fname, "r+");
if (NULL == fp)
fp = fopen(fname, "w+");
if (fp) {
fseek(fp, 0L, SEEK_END);
if (ftell(fp) > 0) {
fseek(fp, -1L, SEEK_END);
fwrite(",", 1, 1, fp);
fwrite([data bytes] + 1, [data length] - 1, 1, fp);
}
else
fwrite([data bytes], [data length], 1, fp);
fclose(fp);
}
append data to .json file with PHP
also keep with valid json structure
not append array.
append json to QuesAns.json file.
overwrite data in file
$data = $_POST['data'];
//$data=
array("Q"=>"QuestThird","A"=>"AnswerThird");
$inp = file_get_contents('QuesAns.json');
//$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';
/**Convert to array because array_push working with array**/
$tempArray = json_decode($inp,true);
array_push($tempArray, $data);
print_r($tempArray);
echo'<hr>';
$jsonData = json_encode($tempArray);
file_put_contents('QuesAns.json', $jsonData);
print($jsonData);
Output:
Array ( [0] => Array ( [Q] => QuestFurst [A] => AnswerFirst ) [1] => Array ( [Q] => Quest second [A] => AnswerSecond ) [2] => Array ( [Q] => QuestThird [A] => AnswerThird ) )
[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"},{"Q":"QuestThird","A":"AnswerThird"}]
/*
* #var temp
* Stores the value of info.json file
*/
$temp=file_get_contents('info.json');
/*
* #var temp
* Stores the decodeed value of json as an array
*/
$temp= json_decode($temp,TRUE);
//Push the information in temp array
$temp[]=$information;
// Show what new data going to be written
echo '<pre>';
print_r($temp);
//Write the content in info.json file
file_put_contents('info.json', json_encode($temp));
}
I wrote this PHP code to add json to a json file.
The code will enclose the entire file in square brackets and separate the code with commas.
<?php
//This is the data you want to add
//I am getting it from another file
$callbackResponse = file_get_contents('datasource.json');
//File to save or append the response to
$logFile = "results44.json";
//If the above file does not exist, add a '[' then
//paste the json response then close with a ']'
if (!file_exists($logFile)) {
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists but is empty, add a '[' then
//paste the json response then close with a ']'
else if ( filesize( $logFile) == 0 )
{
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists and contains some json contents, remove the last ']' and
//replace it with a ',' then paste the json response then close with a ']'
else {
$fh = fopen($logFile, 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh);
$log = fopen($logFile, "a");
fwrite($log, ','.$callbackResponse. ']');
fclose($log);
}
?>
GoodLuck
I have this code:
libxml_use_internal_errors(TRUE);
$dom = new DOMDocument;
$dom->Load('/home/dom/public_html/cache/feed.xml');
$xmlor = '/home/dom/public_html/cache/feed.xml';
// open file and prepare mods
$fh = fopen($xmlor, 'r+');
$data = fread($fh, filesize($xmlor));
$dmca_claim_jpg = array( 'baduser_.jpg','user78.jpg' );
$dmca_claim_link = array( 'mydomain.com/baduser_','mydomain.com/user78' );
echo "Opening local XML for edit..." . PHP_EOL;
$new_data = str_replace("extdomain.com", "mydomain.com", $data);
$new_data2 = str_replace($dmca_claim_jpg, "DMCA.jpg", $data);
$new_data3 = str_replace($dmca_claim_link, "#", $data);
fclose($fh);
// run mods
$fh = fopen($xmlor, 'r+');
fwrite($fh, $new_data);
fwrite($fh, $new_data2);
fwrite($fh, $new_data3);
echo "Updated feed URL and DMCA claims in local XML..." . PHP_EOL;
fclose($fh);
It does not give any errors when executing but messes up the xml file by removing the first two lines (weird) when fwriting $new_data2 and $new_data3 to xml file.
It works fine writing only $new_data...
I think it has to do with the $dmca_claim_jpg/link arrays.
Parse XML using SimpleXML or DOMDocument it's cleaner and you have a standard OOP way of accessing nodes
I have a JSON file badly formatted (doc1.json):
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192}
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472}
{...}{...}
And I have to change it in this:
{"u":[
{"text":"xxx","user":{"id":96525997,"name":"ss"},"id":29005752194568192},
{"text":"yyy","user":{"id":32544632,"name":"cc"},"id":29005753951977472},
{...},{...}
]}
Can I do this in a PHP file?
//Get the contents of file
$fileStr = file_get_contents(filelocation);
//Make proper json
$fileStr = str_replace('}{', '},{', $fileStr);
//Create new json
$fileStr = '{"u":[' . $fileStr . ']}';
//Insert the new string into the file
file_put_contents(filelocation, $fileStr);
I would build the data structure you want from the file:
$file_path = '/path/to/file';
$array_from_file = file($file_path);
// set up object container
$obj = new StdClass;
$obj->u = array();
// iterate through lines from file
// load data into object container
foreach($array_from_file as $json) {
$line_obj = json_decode($json);
if(is_null($line_obj)) {
throw new Exception('We have some bad JSON here.');
} else {
$obj->u[] = $line_obj;
}
}
// encode to JSON
$json = json_encode($obj);
// overwrite existing file
// use 'w' mode to truncate file and open for writing
$fh = fopen($file_path, 'w');
// write JSON to file
$bytes_written = fwrite($fh, $json);
fclose($fh);
This assumes each of the JSON object repsentations in your original file are on a separate line.
I prefer this approach over string manipulation, as you can then have built in checks where you are decoding JSON to see if the input is valid JSON format that can be de-serialized. If the script operates successfully, this guarantees that your output will be able to be de-serialized by the caller to the script.
I have this .json file:
[
{
"id": 1,
"title": "Ben\\'s First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\'s Second Blog Post",
"content": "This is the content"
}
]
This is my PHP code:
<?php
$data[] = $_POST['data'];
$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);
The thing is, I'm not exactly sure how to achieve it. I'm going to call this code above every time a form is submitted, so I need the ID to increment and to also keep the valid JSON structure with [ and {, is this possible?
$data[] = $_POST['data'];
$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.
// read the file if present
$handle = #fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
You're ruining your json data by blindly appending text to it. JSON is not a format that can be manipulated like this.
You'll have to load your json text, decode it, manipulate the resulting data structure, then re-encode/save it.
<?php
$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));
Let's say you've got [1,2,3] stored in your file. Your code could turn that into [1,2,3]4, which is syntactically wrong.
Sample code I used to append additional JSON array to JSON file.
$additionalArray = array(
'id' => $id,
'title' => $title,
'content' => $content
);
//open or read json data
$data_results = file_get_contents('results.json');
$tempArray = json_decode($data_results);
//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
If you want to add another array element to a JSON file as your example shows, open the file and seek to the end. If the file already has data, seek backwards one byte to overwrite the ] following the last entry, then write , plus the new data minus the initial [ of the new data. Otherwise, it's your first array element, so just write your array normally.
Sorry I don't know enough about PHP to post actual code, but I've done this in Obj-C and it's allowed me to avoid reading the whole file in first just to add onto the end:
NSArray *array = #[myDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
FILE *fp = fopen(fname, "r+");
if (NULL == fp)
fp = fopen(fname, "w+");
if (fp) {
fseek(fp, 0L, SEEK_END);
if (ftell(fp) > 0) {
fseek(fp, -1L, SEEK_END);
fwrite(",", 1, 1, fp);
fwrite([data bytes] + 1, [data length] - 1, 1, fp);
}
else
fwrite([data bytes], [data length], 1, fp);
fclose(fp);
}
append data to .json file with PHP
also keep with valid json structure
not append array.
append json to QuesAns.json file.
overwrite data in file
$data = $_POST['data'];
//$data=
array("Q"=>"QuestThird","A"=>"AnswerThird");
$inp = file_get_contents('QuesAns.json');
//$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';
/**Convert to array because array_push working with array**/
$tempArray = json_decode($inp,true);
array_push($tempArray, $data);
print_r($tempArray);
echo'<hr>';
$jsonData = json_encode($tempArray);
file_put_contents('QuesAns.json', $jsonData);
print($jsonData);
Output:
Array ( [0] => Array ( [Q] => QuestFurst [A] => AnswerFirst ) [1] => Array ( [Q] => Quest second [A] => AnswerSecond ) [2] => Array ( [Q] => QuestThird [A] => AnswerThird ) )
[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"},{"Q":"QuestThird","A":"AnswerThird"}]
/*
* #var temp
* Stores the value of info.json file
*/
$temp=file_get_contents('info.json');
/*
* #var temp
* Stores the decodeed value of json as an array
*/
$temp= json_decode($temp,TRUE);
//Push the information in temp array
$temp[]=$information;
// Show what new data going to be written
echo '<pre>';
print_r($temp);
//Write the content in info.json file
file_put_contents('info.json', json_encode($temp));
}
I wrote this PHP code to add json to a json file.
The code will enclose the entire file in square brackets and separate the code with commas.
<?php
//This is the data you want to add
//I am getting it from another file
$callbackResponse = file_get_contents('datasource.json');
//File to save or append the response to
$logFile = "results44.json";
//If the above file does not exist, add a '[' then
//paste the json response then close with a ']'
if (!file_exists($logFile)) {
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists but is empty, add a '[' then
//paste the json response then close with a ']'
else if ( filesize( $logFile) == 0 )
{
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists and contains some json contents, remove the last ']' and
//replace it with a ',' then paste the json response then close with a ']'
else {
$fh = fopen($logFile, 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh);
$log = fopen($logFile, "a");
fwrite($log, ','.$callbackResponse. ']');
fclose($log);
}
?>
GoodLuck