[英]Submitting formatted JSON with PHP form
<form name="postform" action="post.php" method="post" enctype="multipart/form-data">
<table class="postarea" id="postarea">
<tbody>
<tr> <td class="postblock">Date:</td><td><input type="text" name="startDate"></td></tr>
<tr> <td class="postblock">Title:</td><td><input type="text" name="headline"></td></tr>
<tr> <td class="postblock">Article:</td><td><textarea id="text" rows="5" cols="30" type="text" name="text"></textarea> </td> </tr>
<tr> <td class="assetblock">Image address:</td><td><input type="text" name="media"></td></tr>
<tr> <td class="assetblock">Image caption:</td><td><input type="text" name="caption"></td></tr>
<tr> <td class="postblock"></td><td> <input type="submit" value="Submit Entry"> </td> </tr>
</tbody>
</table>
</form>
</form>
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$json = json_encode( $_POST );
// make sure there were no problems
//if( json_last_error() != JSON_ERROR_NONE ){
//exit; // do your error handling here instead of exiting
// }
$file = 'entries.json';
// write to file
// note: _server_ path, NOT "web address (url)"!
file_put_contents( $file, $json, FILE_APPEND);
}
我正在嘗試創建一個表單,該表單將允許我的用戶向該站點添加條目。 條目存儲在JSON文件中。 我創建了一個提交給JSON表單的表單,其格式如下:
{"startDate":"example",
"headline":"example",
"text":"example",
"media":"example",
"caption":"example"}
媒體和字幕與圖像,視頻或其他多媒體有關,我需要將它們存儲為單獨的對象,如以下示例所示。
{"startDate":"example",
"headline":"example",
"text":"example",
"asset" :{"media":"example",
"caption":"example"}
}
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$postArray = array(
"startDate" => $_POST['startDate'],
"headline" => $_POST['headline'],
"text" => $_POST['text'],
"asset" => array(
"media" => $_POST["media"],
"caption" => $_POST['caption']
)
); //you might need to process any other post fields you have..
$json = json_encode( $postArray );
// make sure there were no problems
//if( json_last_error() != JSON_ERROR_NONE ){
//exit; // do your error handling here instead of exiting
// }
$file = 'entries.json';
// write to file
// note: _server_ path, NOT "web address (url)"!
file_put_contents( $file, $json, FILE_APPEND);
}
你知道json_encode嗎? 只需將給定結構的關聯數組傳遞給此函數
創建一個新的數組,即,並將其傳遞給json_encode
$array = array(
"startDate" => $_POST['startDate'],
//..
"assets" => array(
"media" => $_POST["media"]
//..
)
);
$json = json_encode($array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.