Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

javascript - Creating .JSON file with PHP

I have a basic form that includes an input and a submit button. I'd like the value of the input to be converted into JSON and then that JSON to be placed in a file on the server for use later. I'm using AJAX and a small PHP script to handle the data and the file creation, however the JSON file (test.json) is never created.

HTML Markup

<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"
    }
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"}]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...