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.
Related
I try to read JSON stream with an ZIP file
but i can't read this zip for get data with JSON
code :
$url = 'https://website.com/wb9f4a8e744a1'; // when we click here is an ZIP file
$z = new ZipArchive();
if ($z->open($url)) {
$json = $z->getFromName("index.json");
if ($json) {
//decode json array
$json_array = json_decode($json);
var_dump($json_array);
}
}
tree of zip file :
index.json
Objects (folder) // i need to read also this folder and subfolder
2/9/289892.json
4/z/24522.json
v/9a/45582.json
After the code who run (when i unzip folder in FTP)
$data = file_get_contents($url);
$characters = json_decode($data);
foreach ($characters as $character) {
echo $character->label . '<br>';
$dossier = 'objects/' . $character->file;
$data2 = file_get_contents($dossier);
$characters2 = json_decode($data2, true);
thank you
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 a json file which is read by php and i want to change one object of the json file using php now my code looks like this but it doesn't work so how should I do? (the obj_name in the son object should be modified to $name)
<?php
$json = $_POST['myobj'];
$data = json_decode($json,true);
$name = xxxxxxxxx;
$data['obj_name'] = "$name";
#json = json_encode($data);
$filename = xxxxxxxxxxxxx
$file = fopen($filename,'w+');
fwrite($file, $json);
fclose($file);
?>
The # is commenting out your code and it should be a $ to make it a variable.
So, change this:
#json = json_encode($data);
to this:
$json = json_encode($data);
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
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