(PHP) Add incorrect text to json file

json decode php
php read json file
how to get data from json array in php
php json_decode example
php json stringify
php parse json array
json_unescaped_unicode
php json_encode utf8

My php script add incorrect value and overwrite the text of my json.json so I want don't overwrite it and add in the text with this format:

{
    name:"Google",
    url: "google.es",
},

and the script add the text as: ["{'name':'gmail', 'url':'gmail.com'}"] The objective is don't overwrite, just add content to the existing code.

html:

<!DOCTYPE html>
<html>

<head>
    <title>SSL Checker</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript" src="js/json.json" charset="utf-8"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $jsonContents = file_get_contents('js/json.json');
    $name = $_POST['addname'];
    $url = $_POST['addlink'];
    $data = json_decode($jsonContents, true);
    $data[] = array("{'name':'$name', 'url':'$url'}");
    $json = json_encode($data);
    file_put_contents('js/json.json', $json);
}
?>
</head>
<body onLoad="start()">
    <div id="title">
        <h1>SSL Checker</h1>
    </div>
    <div id="data">
        <form method="POST" onsubmit="SSL.Add()">
            <input type="text" name="addname" id="add-name" placeholder="Name"></input>
            <input type="text" name="addlink" id="add-link" placeholder="Link"></input>
            <input type="submit" value="Add">
        </form>
        <div id="edit" role="aria-hidden">
            <form action="javascript:void(0);" method="POST" id="saveEdit">
                <input type="text" id="edit-name">
                <input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">&#10006;</a>
            </form>
        </div>
        <p id="counter"></p>
    </div>
    <div id="table">
        <table style="overflow-x:auto;">
            <tr>
                <th>Sites:</th>
            </tr>
            <tbody id="urls">
            </tbody>
        </table>
    </div>
</body>
</html>

JSON file:

var Checker = [{
        name:"Google",
        url: "google.es",
    },
    {
        name:"Yahoo",
        url: "yahoo.com",
    }
]

js:

function start() {
    var SSL = new function() {
        //List urls to check
        this.el = document.getElementById('urls');
        this.Count = function(data) {
            var el = document.getElementById('counter');
            var name = 'url';

            if (data) {
                if (data > 1) {
                    name = 'urls';
                }
                el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
            } else {
                el.innerHTML = 'No ' + name;
            }
        };
        //Box/Table Configuration (Sites/edit/delete)
        this.FetchAll = function() {
            var data = '';

            if (Checker.length > 0) {
                for (i = 0; i < Checker.length; i++) {
                    data += '<tr>';
                    data += '<td><a href="http://' + Checker[i].url + '">' + Checker[i].name + '</a></td>';
                    data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
                    data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
                    data += '</tr>';

                }
            }

            this.Count(Checker.length);
            return this.el.innerHTML = data;
        };
        //Add name
        this.Add = function() {
            el = document.getElementById('add-name');
            el1 = document.getElementById('add-link')
            var url = el.value;
            var url1 = el1.value;
            if (url) {
                if (url) Checker.push({
                    "name": url,
                    "url": url1
                })
                el.value = '';
                this.FetchAll();
            }
        }

        //Edit
        this.Edit = function(item) {
            var el = document.getElementById('edit-name');
            var el1 = document.getElementById('edit-name1');
            el.value = Checker[item].name;
            el1.value = Checker[item].url;
            document.getElementById('edit').style.display = 'block';
            self = this;
            document.getElementById('saveEdit').onsubmit = function() {
                var url = el.value;
                var url1 = el1.value;
                if (url) {
                    Checker[item].url = url1.trim();
                    Checker[item].name = url.trim();
                    self.FetchAll();
                    CloseInput();
                }
            }
        };
        //Delete
        this.Delete = function(item) {
            Checker.splice(item, 1);
            this.FetchAll();
        };

    };

    SSL.FetchAll();
    //Close button (Edit bar)
    function CloseInput() {
        document.getElementById('edit').style.display = 'none';
    }
    window.CloseInput = CloseInput;
    window.SSL = SSL;
}

You need to load old JSON first and push in that array

$json = json_parse(file_get_contents('js/json.json'));
if(!$json){ $json = []; };
$json[] = ['name' => $name, 'url' => $url];
$json = json_encode($json);
file_put_contents('js/json.json', $json);

json_decode - Manual, json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int to allow comments works except if there is a comment at the very beginning of the file. this. and It works well~~~hope this helps us, and add to the Array function list. - The PHP code in "save_json.php" that gets data from this form, and saves it into a text file, in JSON format (see the comments in code). - If the text file already exists, with some data, the code from this example will rewrite the data from that text file with the new form data .


SOLVED: The problem was that I was trying to "encode" with the json structure I changed array("{'name':'$name', 'url':'$url'}"); for :

$data[] = array(
    'name' => $name,
    'url' => $url
);

It solved the issue with the format. And for introduce the values into the json file created I removed

var Checker =

From a JSON file and removed:

<script type="text/javascript" src="js/json.json" charset="utf-8"></script>

and I put:

 <script type="text/javascript" charset="utf-8">
        var Checker = <?php echo file_get_contents('js/json.json'); ?>;
    </script>

On the html page

json_last_error - Manual, An invalid json string which will cause an syntax add a note for people who may be trying to understand why specific JSON files are not being decoded. Accessing JSON feed URL can be done in various ways. In the above example on parsing JSON file data via PHP, we have used file_get_contents() function. The file_get_contents() will not work on the server because of the security directives enable with the PHP.ini configurations.


The JSON in the json.json file is likely invalid and json_encode returns false or null. If so, when you add new data to $data, it looks like it overwrites, but it really never had any data to start with.

You can verify the validity of your input by var_dump'ing the result of json_encode or by calling json_last_error_msg() or by running your json.json through http://jsonlint.com

Make sure you got quotes around the properties in order for PHP to successfully parse it. Also, you need to change how you add new entries:

$data[] = array("{'name':'$name', 'url':'$url'}");

This adds a single string to the data array and consequently, it will not add an object when using json_encode. Just do

$data[] = array('name' => $name, 'url' => $url);

Example:

<?php

$name = 'Example';
$url = 'http://example.com';

$the_json = json_decode('[{ "name":"Google", "url": "google.es"}, { "name":"Yahoo", "url": "yahoo.com"}]', true);

if (!is_array($the_json)) {
    echo 'Error parsing JSON: ' . json_last_error_msg();
}

$the_json[] = ['name' => $name, 'url' => $url];
echo json_encode($the_json);

Output:

[{"name":"Google","url":"google.es"},{"name":"Yahoo","url":"yahoo.com"},{"name":"Example","url":"http:\/\/example.com"}]

json_encode - Manual, Returns a JSON encoded string on success or FALSE on failure. Add the properties you want to be included in the output into an array in the getIterator()  Using JSON, complex data structures can be saved in a plain text file, readable by a person. In this post we will show how to save and read a JSON-formatted data file from a PHP script. We will use as an example a file named “data.json” with the following contents:


JSON Handling with PHP: How to Encode, Write, Parse, Decode , JSON Handling with PHP by Parsing File Data json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed Add the below script on the HTML page from where you want to access  Note this is not a normal text file it’s a JSON file. That’s why we have used json_decode function to convert data into an array. array_push function will add formdata array into existing json array (arr_data). json_encode() will convert array into JSON format, so that we can write this json into json file. Note, we have used JSON_PRETTY


Append Data to JSON File using PHP, How to Append form data to JSON File in PHP Programming Language. I have create one Duration: 6:12 Posted: Apr 25, 2016 PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.


JSON PHP, Send a request to the PHP file, with the JSON string as a parameter. Wait until the request $obj = json_decode($_GET["x"], false); $conn = new Add the array to an object, and return the object as JSON using the json_encode() function. To use this feature, we import the json package in Python script. The text in JSON is done through quoted string which contains the value in key-value mapping within { }. Functions Used: json.loads(): json.loads() function is present in python built-in ‘json’ module. This function is used to parse the JSON string.