使用PHP和AJAX将数据附加到json文件

时间:2016-04-24 10:52:30

标签: php json

我试图将用户名和密码附加到Json文件中。我花了几个小时拖网浏览这个网站,然后去了很多通常可靠的教程网站(Derek Banas,新波士顿),这是一个操纵,追加和解析Json文件的明确方法,令我惊讶的是我找不到一个。

所以我希望有人能够为我解决这个问题。到目前为止,我已设法覆盖我的Json文件中的数据,将数据追加到最后但不是以对象的形式。我的Json文件看起来像这样;

AJAX:

 {
 "LogIns":[
    {
        "Username":"Mike",
        "password":"123"
    },
    {
        "Username":"Farrah",
        "password":"123"
    },
    {
        "Username":"John",
        "password": "123"
    }

 ]
}

我的HTML和AJAX看起来像这样:

HTML / AJAX:

<body>
<center>
    <fieldset>
        <legend>Please register before playing</legend>
        <form>
            Username: <br>
            <input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
            Password: <br>
            <input type="password" placeholder="Enter a password" id="password" name="password"><br>
            <input type="submit" value="Submit" onclick="return checkLogin();">
        </form>
    </fieldset>
</center>
<br>
<br>
<div id="PHPid">

    <script>
        var usernamePassed = "";
        var userPassword = "";

        function checkLogin(){
            usernamePassed = document.getElementById("username1").value;
            userPassword = document.getElementById("password").value;
            callAJAX();
            return false;

        }
        function callAJAX(){
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange=function() {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    //location.href="gameOption.html";
                    console.log(xhttp.responseText);
                }
            }
            xhttp.open("POST", "reg.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("username=" + usernamePassed + "&password="+ userPassword);
        }

    </script>

PHP文件如下所示:

<?php

            $username = $_POST['username'];
            $password = $_POST['password'];

            $str = file_get_contents('logins.json'); // Save contents of file into a variable
            $json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
            array_push($data, array('Username' => $username, "password" => $password));
            file_put_contents('logins.json', json_encode($json));
?>

我试图添加数据,以便下次有人注册时,我的Json文件将如下所示:

JSON;

{
"LogIns":[
    {
        "Username":"Mike",
        "password":"123"
    },
    {
        "Username":"Farrah",
        "password":"123"
    },
    {
        "Username":"John",
        "password": "123"
    },
    {
        "Username":"Alfred",
        "password": "123"
    }

]
}

使用上面的代码,没有任何内容正在打印到控制台。

我也在我的PHP中试过这个:

$username = $_POST['username'];
            $password = $_POST['password'];

            $str = file_get_contents('logins.json'); // Save contents of file into a variable


            $json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
            $data = array();
            array_push($data, array('Username' => $username, "password" => $password));

           file_put_contents('logins.json', json_encode($json));

哪个也不向控制台输出任何内容,但将Json文件更新为如下所示:

{"LogIns":[
{"Username":"Mike",
"password":"123"},
{"Username":"Farrah",
"password":"123"},
{"Username":"John",
"password":"123"},
{"Username":"Alfred",
"password":"123"},
"Username:","mike",
"password:","123"
]
}

如果有人可以告诉我那会很棒,但是如果他们能够清理覆盖整个文件的方法,那么在上面的子文件中添加一个对象,并从Json文件中删除一个对象,这将是惊人的!

我确定这并不难,但我似乎无法找到答案。

提前致谢!

1 个答案:

答案 0 :(得分:0)

你附加在错误的地方 您应该将新值附加到内部&#39; LogIns`数组,而是将其附加到它的容器中。

<?php

$string = ' {
 "LogIns":[
    {
        "Username":"Mike","password":"123"
    },
    {
        "Username":"Farrah","password":"123"
    },
    {
        "Username":"John","password": "123"
    }
 ]
}';

$array = json_decode($string,true);

$extra = [
    'Username' => 'John',
    'password' => 'doe123'
];

$array['LogIns'][] = $extra;

print_r($array);

输出会很好:

Array
(
    [LogIns] => Array
        (
            [0] => Array
                (
                    [Username] => Mike
                    [password] => 123
                )

            [1] => Array
                (
                    [Username] => Farrah
                    [password] => 123
                )

            [2] => Array
                (
                    [Username] => John
                    [password] => 123
                )

            [3] => Array
                (
                    [Username] => John
                    [password] => doe123
                )

        )

)

如果您在最终阵列上执行json_encode,您将获得以下

{
    "LogIns": [{
        "Username": "Mike",
        "password": "123"
    }, {
        "Username": "Farrah",
        "password": "123"
    }, {
        "Username": "John",
        "password": "123"
    }, {
        "Username": "John",
        "password": "doe123"
    }]
}

另请参阅使用[]=代替array_push,这可以消除使用函数的开销。

您的下一个问题:

  1. 从json对象中删除对象 只需将初始json字符串解码为数组并对数组进行操作,删除unset
    项目 恩。 unset($array['LogIns'][2])将使用键2

  2. 删除元素
  3. 覆盖文件
    file_put_contents已经这样做了,如果您执行想要附加到文件,则需要pass the FILE_APPEND flag