Append data to top of the JSON file using PHP [duplicate] - php

This question already exists:
Add new data to top of the JSON file in PHP [duplicate]
Closed 2 years ago.
I am appending data to JSON file using a PHP form, But right now it adds the new data to the bottom in JSON file
I want to add new data to top in JSON file instead of bottom.
Here is My PHP code which i am using to append data to JSON.
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["author"]))
{
$error = "<label class='text-danger'>Enter Author</label>";
}
else if(empty($_POST["category"]))
{
$error = "<label class='text-danger'>Enter Thumbnail</label>";
}
else if(empty($_POST["url"]))
{
$error = "<label class='text-danger'>Enter URL</label>";
}
else
{
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_POST['name'],
'author' => $_POST["author"],
'category' => $_POST["category"],
'url' => $_POST["url"]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
Here is the wallpaper.JSON currently it adds data like this -
[
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]
I want it like this -
[
{
"name": "New Code",
"author": "New Code",
"category": "New Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
},
{
"name": "Old Code",
"author": "Old Code",
"category": "Old Code",
"url": "https://wallpaperaccess.com/full/11851.jpg"
}
]

Well You can use use array_reverse in your use case but I would do the other approach
$array_data[] = $extra;
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
But a better approach would be to use array_unshift
array_unshift($array_data, $extra);
Source: https://www.php.net/manual/en/function.array-unshift.php

Related

Append data to top of the JSON file using PHP form

I wanted to append a php from data in JSON file to top.
I used some PHP functions like -
array_unshift($array_data, $extra);
$array_data = array_reverse($array_data);
Example -
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["name"]))
{
$error = "<label class='text-danger'>Enter Name</label>";
}
else if(empty($_POST["author"]))
{
$error = "<label class='text-danger'>Enter Author</label>";
}
else if(empty($_POST["category"]))
{
$error = "<label class='text-danger'>Enter Thumbnail</label>";
}
else if(empty($_POST["url"]))
{
$error = "<label class='text-danger'>Enter URL</label>";
}
else
{
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_POST['name'],
'author' => $_POST["author"],
'category' => $_POST["category"],
'url' => $_POST["url"]
);
$array_data[] = $extra;
//array_unshift($array_data, $extra); // used this as well
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
else
{
$error = 'JSON File not exits';
}
}
}
?>
Both of these PHP functions, they work perfectly until you add data 2 times but once you add 3rd data or more then it looks like this -
[
{
"name": "3",
"author": "3",
"category": "3",
"url": "3"
},
{
"name": "1",
"author": "1",
"category": "1",
"url": "1"
},
{
"name": "2",
"author": "2",
"category": "2",
"url": "2"
}
]
But it should look like this -
[
{
"name": "3",
"author": "3",
"category": "3",
"url": "3"
},
{
"name": "2",
"author": "2",
"category": "2",
"url": "2"
},
{
"name": "1",
"author": "1",
"category": "1",
"url": "1"
}
]
At beggining you have [1] then you insert [2] and after $array_data[] = $extra; goes to [1][2] and the you reverse array [2][1]. At this moment when you insert a new value you have [2][1][3] and the after reversing [3][1][2] the solution would be reversing before insert extra:
test.php:
<?php
if(file_exists('wallpaper.json'))
{
$current_data = file_get_contents('wallpaper.json');
$array_data = json_decode($current_data, true);
$extra = array(
'name' => $_REQUEST['name'],
'author' => $_REQUEST["author"],
'category'=> $_REQUEST["category"],
'url' => $_REQUEST["url"]
);
echo $extra['name'];
$array_data = array_reverse($array_data);
$array_data[] = $extra;
$array_data = array_reverse($array_data);
$final_data = json_encode($array_data);
if(file_put_contents('wallpaper.json', $final_data))
{
$message = "<label class='text-success'>File Appended Success fully</p>";
}
}
?>
to run I used to pass parameters:
http://localhost/test.php?name=4&author=4&category=4&url=4
$posted[] = $_POST;
$current_data = file_get_contents('wallpaper.json');
$decoded = json_decode($current_data,true);
//You merge together posted array values with the current array
//that is in the current file (after decoding the json)
//$posted is first part of the array because you start to merge from that
//array
$new_arr = array_merge($posted, $decoded);
//Encode the new array into JSON and save it
$encoded_json = json_encode($new_arr,);
file_put_contents('wallpaper.json', $encoded_json);
First, don't push the $_POST data into its own subarray. It is already in the correct structure to call array_unshift() directly on it. In other words, you don't need to index it -- unshift will apply the 0 key for you.
Code: (Demo)
$fileContents = '[{"name":"B1","author":"B2","category":"B3","url":"B4"},{"name":"A1","author":"A2","category":"A3","url":"A4"}]';
$array = json_decode($fileContents, true);
$_POST = [
'name' => 'C1',
'author' => 'C2',
'category' => 'C3',
'url' => 'C4',
];
array_unshift($array, $_POST);
echo json_encode($array);
Output:
[{"name":"C1","author":"C2","category":"C3","url":"C4"},{"name":"B1","author":"B2","category":"B3","url":"B4"},{"name":"A1","author":"A2","category":"A3","url":"A4"}]
Secondly, I don't support the notion of building this json file if there is any way that you can avoid it. I mean, as you your file size increases, your server will have to work harder and harder and harder to parse the json, manipulate it, re-encode it every time you want to make a change.
I might recommend that you restructure your file to be a txt file which is a collection of json strings -- all of which are separately written on each line. This way you don't have to unpack and repack your data every time, you just prepend the new json string to the file and walk away. *Caveat, this will fail if the data that you are storing contains newline characters -- I don't know if your project might receive such data.
p.s. If you are not a ultra-purist developer and your incoming data is as tame as it looks from your post, you can hack at the json string and lighten the workload like this:
Code: (Demo)
$newJson = json_encode($_POST);
if ($fileContents) {
$fileContents = substr_replace($fileContents, $newJson . ',', 1, 0);
} else {
$fileContent = '[' . $newJson . ']';
}
echo $fileContents;

how to update the value of json data label with the new value using php?

I want to update the label value using PHP. Suppose if I enter the same label then it'll match if there exists any same label named, then it'll update the value of that label.
[{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}]
in that above data.json i want to update the value of label : "yy" to val: "20". For this I'm using this code
$myFile = "data.json";
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'label'=> $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach($arr_data as $item){
}
// array_push($arr_data,$formdata);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
/*this is the matching label code*/
if(in_array($formdata['label'],$item)){
$item['val'] = $formdata['val'];
echo $item['val'];
echo "got it";
}
else echo "not matched";
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Move the code to match label name inside foreach loop so that each label value in json array can be compared. Updated Code:
$myFile = "data.json";
try {
//Get form data
$formdata = array(
'label' => $_POST['label'],
'val' => $_POST['val']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
foreach ($arr_data as $key => $item) {
/* this is the matching label code */
if ($formdata['label'] == $item["label"]) {
$arr_data[$key]["val"] = $formdata['val'];
echo $item['val'];
echo "got it";
} else
echo "not matched";
}
//write json data into data.json file
if (!file_put_contents($myFile, json_encode($arr_data, JSON_PRETTY_PRINT))) {
echo "error";
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Iterative solution with json_decode() and json_encode()
$jsonData = '[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]';
echo '<strong>Before update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
$jsonArray = json_decode($jsonData, true);
foreach ($jsonArray as $key => $jsonRow) {
if (isset($jsonRow['label']) && $jsonRow['label'] == 'yy') {
$jsonArray[$key]['val'] = 20;
}
}
$jsonData = json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '<strong>After update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';
This code will give output
Before update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": "14"
}
]
After update
[
{
"label": "aa",
"val": "12"
},
{
"label": "new",
"val": "13"
},
{
"label": "yy",
"val": 20
}
]
You can use preg_replace.
The pattern of a Json is very predictable.
Using regex means you don't need to decode and encode or even iterate the array.
$label = "yy";
$val = 20;
echo preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
https://3v4l.org/m4rDa
If you need to know if the label has been updated then you can use this:
$label = "yy";
$val = 20;
$new = Preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
"label\": \"" . $label . "\", \"val\": \"". $val,
$json);
If($json != $new){
Echo "label updated\n";
}else{
Echo "nothing found\n";
}
Echo $new;
It will compare the "old" Json with the new and if they don't match the lable has been updated.

Select individual column json in php

{
"responseData": {
"results": [
{
"title": "sobig",
"titleNoFormatting": "test",
},
{
"title": "test 2 ",
"titleNoFormatting": "test 2sd",
},
{
"title": "asdasdasda",
"titleNoFormatting": "asdasdasd",
},
{
"title": "A Warming",
"titleNoFormatting": "A Warming",
}
.
.
.
.
{
"title": "last thing",
"titleNoFormatting": "sada",
}
],
I have json files like this.
for($i=$veri1; $i <= $veri2; $i++) {
$uri = "http://test.com/json/".$i."/0";
$json = json_decode(file_get_contents($uri));
if($json->data->price >= $nakit && $json->data->odds >= $oran)
{
I'm getting some data with this code correctly from another json file.
i want get data from first json code, if "title" == "sobig" . How can I do that.
$json->responseData->results->title == sobig is not working. How can I get data if title is sobig
$json= json_decode($response, true);
foreach ($json['responseData']['results'] as $key => $value) {
if ($value == 'sobig') {
// found it
}
}
Try this example to see if this may fix your issue.
<?php
$json = '{ "responseData": {
"result" : [
{ "title": "sobig" , "titleNo":"test"},
{ "title": "loco" , "titleNo":"test"},
{ "title": "tom" , "titleNo":"test"}
]
}}';
$jsonDecoded = json_decode($json);
foreach ($jsonDecoded->responseData->result as $key => $value) {
var_dump($value); echo '<br>';
if($value->title == 'sobig'){
echo "we did it!!";
echo "<br>";
}
}
?>
I place a couple of var dumps so you can see the stucture of your object and why you need to use the foreach

PHP generate JSON in certain format

So i want to generate my JSON for a angular app in this format. The result will be used for a dropdown and i need it to be in this particular format
[
{
id:1,
post_title:title1},
{
id:2,
post_title:title1},
{
id:3,
post_title:title3},
and so on ...
]
But when i send my JSON back to my angular app it looks like this
{
"0": {
"id": "1",
"post_title": "Batman Ipsum"
},
"1": {
"id": "2",
"post_title": "Title fit for a (precariously enthroned) king"
},
"2": {
"id": "3",
"post_title": "Cupcake Ipsum"
},
"3": {
"id": "4",
"post_title": "The most presidential lorem ipsum in history."
},
"4": {
"id": "5",
"post_title": "Quote Ipsum"
},
"5": {
"id": "6",
"post_title": "Yet another Batman Ipsum"
},
"6": {
"id": "9",
"post_title": "Yet another Harry Potter ipsum"
},
"7": {
"id": "10",
"post_title": "Vegetable Ipsum"
}
}
How to change it to the format that i want?
My php code
function fetchPagesNames()
{
$response = array();
$resultArray=array();
try {
$sql = "SELECT id,post_title FROM posts";
$result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
$resultCount = mysql_num_rows($result);
if ($resultCount > 0) {
while ($row = mysql_fetch_assoc($result)) {
$resultArray[]=$row;
}
$response['status'] = 'Success';
$response['message'] = "Post's Obtained";
$response['results'] = $resultArray;
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
echo json_encode($response,JSON_FORCE_OBJECT);
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}
}
What changes are needed?
There are two major differences between your "required" format and the output you're getting:
The format you've quoted as being required is not actually valid JSON because you're missing the quotes.
The JSON format is very explicit in that it must have quotes around property names and string values. The JSON you're getting outputted is correct in this regard.
Your required output has an outer layer that is an array, whereas your actual output has an object, with numbered elements as strings.
The reason for this is because you're using JSON_FORCE_OBJECT in your call to json_encode(). This argument forces all parts of the JSON otput to be processed as objects not arrays. Remove this and you'll get the top-level array that you're looking for.
Remove JSON_FORCE_OBJECT from json_encode().
Use json_encode for print object.
or look like this...
try {
$sql = "SELECT * FROM tekst";
$result = $dao->conn->query($sql);
//$resultCount = mysql_num_rows($result);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode(
$resultArray
);
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}

How to access multi-level json tree in PHP for database insertion

I am accessing an API where the JSON data is returned as below.
{
"name": "",
"count": 4,
"frequency": "",
"version": 3,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "",
"results": {
"collection": [{
"textlink": {
"href": "http://text1.com",
"text": "Text 1"
},
"index": 1,
"url": ""
}, {
"textlink": {
"href": "http://text2.com",
"text": "Text 2"
},
"index": 2,
"url": ""
}, {
"textlink": {
"href": "http://text3.com",
"text": "Text 3"
},
"index": 3,
"url": ""
}, {
"textlink": {
"href": "http://text4.com",
"text": "Text 4"
},
"index": 4,
"url": ""
}]
}}
As you can see the JSON tree returned has multi-step levels. I am wanting to be able to take some of the deeper levels, in PHP, and insert into a database.
Currently I am using this code to try and echo the data (once I am able to I can then work on inserting it to a database no problem)
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);
foreach($results as $item) {
echo $item->results[0]->collection[0]->textlink[0]->href;
echo "<br>";
echo $item->results->collection['href'];
echo "<br>";
echo $item->results->collection['text'];
}
?>
As you can see above I have tried several ways to access the deeper levels f data that are being displayed but with no avail.
I am currently getting errors of 'trying to get property of a non-object'. How is it possible to reach the data in this array?
try:
echo $results['results']['collection'][0]['textlink']['href'];
$obj = json_decode( $json, true ); foreach ( $obj['key'] as $key => $value ) { echo $value; }
foreach ($response['results']['collection'] as $textlink) {
$row = $textlink['textlink'];
echo $row['href'];
echo "<br>";
echo $row['text'];
echo "<br>";
}
you can do foreach like this, which loops only items in collection
I would suggest to do something like this (According to me, correct way to fetch results from API responses):
<?php
$request = "API.REQUEST.NET";
$response = file_get_contents($request);
$response = json_decode($response);
foreach($response->results->collection as $item) {
echo $item->textlink->href;
echo "<br>";
echo $item->textlink->text;
echo "<br>";
echo $item->index;
echo "<br>";
echo $item->url;
}
?>

Categories