How do guys suggest to share a constants file between PHP and JavaScript, in order not to repeat code? XML file? I am assuming mixing up javascipt inside PHP would not be the right solution!? Thanks
http://php.net/manual/en/book.json.php
I would say use json. It is native to the javascript and there is a parser library for the php.
consider the following:
json:
{constants : { var1 : "value 1", var2 : "value 2", var3 : "value 3"}}
and then read it into php:
$const = json_decode(json_string);
This gives you the object $const with properties like $const->{'var1'} returning "value 1".
in JavaScript this would be:
var const = eval(json_string);
and would give you const.constants.var1 == "value 1".
Easiest implementation in real terms for js is:
<script type="text/javascript" src="json_constants_file.js"></script>
When added the html output you instantly have a constants object with the other objects as its children.
Config variables to be shared by both PHP and JavaScript could easily be stored as XML, yes. JSON might be a better solution, though, as it requires minimal effort to parse - JS handles it natively, and PHP turns it into an array with json_decode
.