简体   繁体   中英

Write data to a json file from PHP file

I have a test.php page which displayes three has 3 "Add Link" buttons, on clicking the buttons the user sees a popup window. In the window he adds the link. Once the link is added , the base page will change from "Add link" button to hyperlink with the new link. Now, I have to pass the new link I receive from the user from test.php to links.php using an ajax call. Links.php has to have a JSON code to write the link to another file called first.json. first.jason will have key value pair for variable and link. I would have to retrieve the value from .json file later and reconstruct into an array, update the corresponding variable and save it back.

I have by far, managed to get the new link from test.php and able to send the same via ajax call to links.php. I am also able to display the link I receive and have verified the same. Now, I would like to copy the link into .json file as a key vale pair. I am new to json and unable to figure out how to go about it. My variable $p, in links.php has the link.

Any pointers on the same will be helpful. Thanks.

Below is my code in test.php:

         <!DOCTYPE html>
        <html>
        <body>   
        <div id="demos1">
    <button id="demo1" onclick="Link1()">Add Link-1</button>  
             <br>
    </div>
    <div id="demos2">
    <button id="demo2" onclick="Link2()">Add Link-2</button>
            <br>
    </div>
    <div id="demos3">
    <button id="demo3" onclick="Link3()">Add Link-3</button>
            <br>
            </div>
    <div id="txtHint"></div>
    <script>
           function Link1()
           {
            var demo1 = document.getElementById('demo1');
            var demos1 = document.getElementById('demos1');
            var value1 = prompt("Please Enter the Link"); 
            var link1 = document.createElement('a'); 
            link1.setAttribute('href', value1); 
            link1.innerHTML = "New Link1";                              
            demo1.parentNode.removeChild(demo1);
            demos1.appendChild(link1);  
            sendlink(value1);
            }
        function Link2()
           {
            var demo2 = document.getElementById('demo2');
            var demos2 = document.getElementById('demos2');
            var value2 = prompt("Please Enter the Link"); 
            var link2 = document.createElement('a'); 
            link2.setAttribute('href', value2); 
            link2.innerHTML = "New Link2"; 
            demo2.parentNode.removeChild(demo2);
            demos2.appendChild(link2);
            sendlink(value2);
            }
        function Link3()
           {
            var demo3 = document.getElementById('demo3');
            var demos3 = document.getElementById('demos3');
            var value3 = prompt("Please Enter the Link"); 
            var link3 = document.createElement('a'); 
            link3.setAttribute('href', value3); 
            link3.innerHTML = "New Link3"; 
            demo3.parentNode.removeChild(demo3);
            demos3.appendChild(link3);  
            sendlink(value3);
             }
        function sendlink(str)
        {
            if (str.length==0)
              { 
              document.getElementById("txtHint").innerHTML="hello";
              return;
              }
            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {

               document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
                }
              }
            xmlhttp.open("GET","links.php?q="+str,true);
            xmlhttp.send();
        }
    </script>
         </body>

          </html>

Below is the code for links.php which receives the value(ie, link) the test.php sends through ajax call:

<?php
include 'test.php';
$p=$_REQUEST['q'];
?>

I am able to write to json file using json_encode. Now I would have to read the link from .json file, associate it to the corresponding variable and save it back. How would I go about this?

To write the json:

file_put_contents('filename.json', json_encode($p));

To read the json:

$p = json_decode(file_get_contents('filename.json'));

Obviously this does no error checking at all though.

if you want to insert the data in json file below one is usefull

function exportToJson() {

    mysql_connect("localhost", "root", "");
    mysql_select_db("krasimir_benchmark");      

    $res = mysql_query("SELECT * FROM users ORDER BY id");
    $records = array();
    while($obj = mysql_fetch_object($res)) {
        $records []= $obj;
    }
    file_put_contents("data.json", json_encode($records));

}

If you have created your json already, then you can simply do this:

fwrite("yourjson.json",json_encode($yourvariablewithdata))

If you have NOT created your json file, then you could create it with fopen function. See details http://www.php.net/manual/es/function.fopen.php

You can always JSON.stringify the JSON on the client side with jQuery, like so:

var dataForJson = JSON.stringify(your_aray);

Then on the server side write it as is (no need for json_encode):

$jsondata = $_POST['dataForJson'];
$writeJson = file_put_contents('data_en.json', $jsondata);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM