python小菜 2017-05-09 09:54 采纳率: 0%
浏览 24

如何用PHP创建.JSON文件?

我有一个基本形式,包括一个 input 和一个提交 button。我希望将 input的值转换为 JSON,然后将该 JSON 放置在服务器上的文件中以供后来使用。 我正在使用AJAX和一个小的 PHP 脚本来处理数据和文件创建,但是 JSON 未创建。

HTML标记:

<input id="title" type="text" name="title" value="Page Title"/>
<button type="submit" value="submit" id="submit">Submit</button>

JS:

var submit = $('#submit');
var title = $('#title');

function createJSON() {
    var jsonObj = [];
    title.each(function() {

        var value = $(this).val();
        var item = {};
        item.title = value;
        jsonObj.push(item);
    });

    $.ajax({
        url:     "create-file.php",
        data: {
            data: jsonObj
        },
        type: "POST"
    });   
}

submit.on('click', function() {
    createJSON();
});

PHP (create-file.php):

<?php
    $json = $_POST['data'];
    $info = json_encode($json);
    $file = fopen('test.json','w+') or die("File not found");
    fwrite($file, $info);
    fclose($file);
?>

JSON:

[
    {
        title: "Page Title"
    }
]
  • 写回答

2条回答 默认 最新

  • weixin_33725239 2017-05-09 10:05
    关注

    Hi You need to write like below code:

    $json = $_POST['data'];//$_POST['json'];    
    $info = json_encode($json);    
    $file = fopen('test.json','w+') or die("File not found");
    fwrite($file, $info);
    fclose($file);
    die;
    

    it will write json in file test.json like [{"title":"Page Title"}]

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?