gpt4 book ai didi

php - 使用 PHP 表单提交格式化的 JSON

转载 作者:可可西里 更新时间:2023-11-01 00:06:08 25 4
gpt4 key购买 nike

文件

索引.php

<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>

post.php

<?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);
}

关于php - 使用 PHP 表单提交格式化的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12643152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com