Reputation: 43
Previously I'm using php to append form data into json file. Currently I am working on php file instead of json file and it has two parameteres and it is shown to users as given in figure Image url link
My Form is
<form action="process.php" method="POST">
Name:<br>
<input type="text" name="name">
<br><br/>
Download Url:<br>
<input type="text" name="downloadUrl">
<br><br>
<input type="submit" value="Submit">
</form>
My php file is
{"downloadurl":[
{"name":"भाद्र ६ : LCR Series",
"downloadurl":"https://drive.google.com/uc?export=download&id=1In76AN2Y5_qXV5ucXDXWx1PTKTTIvD3d"
},
{"name":"भाद्र ६ : LCR Parallel",
"downloadurl":"https://drive.google.com/uc?export=download&id=1R9Ia4X12JZMsTn_vF6z443K6wKI2Rfeu"
}
]}
How can I use append new data such that when submit button is clicked a new data is added on top of above php file such that new file will be
{"downloadurl":[
{"name":"भाद्र ६ : New appended Data",
"downloadurl":"This is new Text added on Top"
},
{"name":"भाद्र ६ : LCR Series",
"downloadurl":"https://drive.google.com/uc?export=download&id=1In76AN2Y5_qXV5ucXDXWx1PTKTTIvD3d"
},
{"name":"भाद्र ६ : LCR Parallel",
"downloadurl":"https://drive.google.com/uc?export=download&id=1R9Ia4X12JZMsTn_vF6z443K6wKI2Rfeu"
}
]}
at top such that it will be displayed to user
Upvotes: 1
Views: 169
Reputation: 1172
From your question, I think that this will solve your question. I'm using array_unshift()
because your use of the phrase on top
leads me to think that you would like to display the data before the existing data, if this is not correct, replace array_unshift()
with array_push()
so that it adds after the data, or see solution 2.
Solution 1:
<?php
//This is where your JSON file is located
$jsonFile = '/path/to/json/file';
//Get the contents of your JSON file, and make it a useable array.
$JSONString = json_decode( file_get_contents( $jsonFile ), true );
//This is the new data that you want to add to your JSON
$newData = array(
//Your data goes here
);
//Add the new data to the start of your JSON
array_unshift($existingData, $newData);
//Encode the new array back to JSON
$newData = json_encode( $existingData, JSON_PRETTY_PRINT );
//Put the JSON back into the file
file_put_contents($jsonFile, $newData);
?>
Solution 2:
<?php
//This is where your JSON file is located
$jsonFile = '/path/to/json/file';
//This is the new data that you want to add to your JSON
$newData = array(
//Your data goes here
);
//Encode the new data as JSON
$newData = json_encode( $newData, JSON_PRETTY_PRINT );
//append the new data to the existing data
file_put_contents( $jsonFile, $newData, FILE_APPEND );
?>
Upvotes: 0
Reputation: 150
I don't understand why you want to append text at the end of a PHP file, but you can use file_put_contents()
with the FILE_APPEND
flag.
Upvotes: 1