Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...