Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(i.e, 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?

like image 380
user2521326 Avatar asked Jul 12 '13 20:07

user2521326


People also ask

Can PHP write to a JSON file?

Using PHP scripting we can store a form value in array format. After that will convert the array into JSON data using json_encode() predefined function. Then at last we can move the data to JSON format file.

How do I push data into a JSON file?

push(newData); To write this new data to our JSON file, we will use fs. writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it.

How encode JSON in PHP?

Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.


2 Answers

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.

like image 119
D-Rock Avatar answered Oct 03 '22 14:10

D-Rock


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));

}
like image 32
Ravi Mane Avatar answered Oct 03 '22 13:10

Ravi Mane