Joanmi
Joanmi

Reputation: 442

(PHP) Add incorrect text to json file

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

Upvotes: 3

Views: 94

Answers (3)

Joanmi
Joanmi

Reputation: 442

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

Upvotes: 1

Gordon
Gordon

Reputation: 317137

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

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39724

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

Upvotes: 1

Related Questions