How to write Javascript object with PHP

My frontend website is currently using a .js file that is hosted by Dropbox as a "database". It is essentially a Javascript dictionary that is called and then used. This is the format.

myDictionary = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}
myDictionary2 = {
"Tag1":["Tag1","info1","info2"],
"Tag2":["Tag2","info1","info2"],
...
...

}

      

I am starting to migrate to PHP and I wanted to know if it is possible to add new entries to this dictionary without messing things up. Basically I'm asking if there is a way to add a dictionary to javascript, preferably just without adding text as it can get complicated. Thank!

+3


source to share


2 answers


Yes, it is possible to use json_decode()

and json_encode()

:

<?php

$myDictionary = json_decode('{
    "Tag1":["Tag1","info1","info2"],
    "Tag2":["Tag2","info1","info2"]
}');

$myDictionary->Tag3 = ["Tag3","info1","info2"];

echo json_encode($myDictionary, JSON_PRETTY_PRINT);

      



Output:

{
    "Tag1": [
        "Tag1",
        "info1",
        "info2"
    ],
    "Tag2": [
        "Tag2",
        "info1",
        "info2"
    ],
    "Tag3": [
        "Tag3",
        "info1",
        "info2"
    ]
}

      

+4


source


First of all, I highly recommend that you use JSON to store your data. Then use AJAX to load the file and parse its contents with JSON.parse()

to get the resulting JavaScript object.

Your example might look something like this:

[{
    "Tag1":["Tag1","info1","info2"],
    "Tag2:"["Tag2","info1","info2"]
},
{
    "Tag1":["Tag1","info1","info2"],
    "Tag2:"["Tag2","info1","info2"]
}]

      

Then you parse the JSON like so:

var dictionaries = JSON.parse(jsonstring);

      



As for your question regarding file manipulation, it needs to be done using the API. You will need to handle this backend (in PHP) since you don't want to give the client (or indeed the rest of the world) access to your Dropbox account. This is probably not as direct as one would like. However, this way you can verify that what you store in the file is valid and won't cause a mess when someone tries to access the (possibly corrupted) file.

See: Using the Core API in PHP .

However, I believe you really want just JSON DB. A quick search turned out to be TaffyDB . Perhaps there are others. I have no experience with TaffyDB, but it doesn't look too complicated to use and is widely used.

However, if this is something that many people will be using at the same time, I strongly suggest that you take the time it takes to build a good and most importantly SAFE solution using a reliable database ( MongoDB , CouchDB or any other database based on document).

+1


source







All Articles