Reputation: 771
Usually we use json(as it is a better option than php's serialization) to transfer a php array into JS to access it from there, or we can use cookie. But can't we do the same thing without those? For example lets take a look at the first code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
$elements = array('myname', 'myage');
?>
<script type="text/javascript">
var elements = <?php echo json_encode($elements) ; ?> ;
//use the elements array afterwards
</script>
</body>
</html>
But we can access that php array without using json, like this way also
<script type="text/javascript">
var elements = [];
<?php foreach($elements as $element) : ?>
elements.push("<?php echo $element; ?>");
<?php endforeach; ?>
//use the elements array afterwards
</script>
So other than secutity reason why do we need json here?
Upvotes: 0
Views: 113
Reputation: 3049
jsonencode()
converts the php array into a string in json format. It is one php call handled locally by the server.
The foreach alternative mixes server and js execution to obtain a similar result. It is more complex to read and longer to execute, both for the server and the javascript client.
Javascript strings can be delimited by " or '. If they are delimited by " and the string contains ", that would signal an end of string, the remainder or the string would be handled as code, leading to a parsing error. Therefore, the " must be escaped like so \". json_encode()
does that for you, echo
doesn't.
So keep to the first.
Upvotes: 1
Reputation: 14423
Keep in mind that you are actually printing a lot of javascript push functions.
I guess the real advantages of JSON comes at the time when using AJAX calls. You'll have no help from PHP to parse the information straight into your javascript script block.
Upvotes: 1
Reputation: 17598
There are a number of special cases you would need to address when embedding php variables in javascript (which json_encode
already handles for you).
For strings:
For numbers:
For arrays:
** Not an exhaustive list, there are probably a few other cases.
It's very easy to make a mistake when writing your own encoding script, and it'll most likely run slower than the PHP json_encode function.
Upvotes: 2