Using PHP's json_encode with Scalar Data

JSON was originally intended for and is usually applied to objects and arrays, but it can also be used with scalar values. The following demonstrates using json_encode to pass a boolean, a number, and a string to JavaScript:

<?php
$bool = false;
$num = 3 + 4;
$str = "A string here";
?>
<script type="text/javascript">
var bool = <?php echo json_encode($bool); ?>; // false
var num = <?php echo json_encode($num); ?>; // 7
var str = <?php echo json_encode($str); ?>; // "A string here"
</script>

Notice that boolean and number data types are preserved when json_encode is used to output the values, in contrast to the old-school approach.

Some problem characters in string variables can also be dealt with through the use of json_encode. The following strings output the old-fashioned way trigger JavaScript errors:

<?php
$str = 'A "string" here';
$long_str = "A longer string
     with a line break";
?>
<script type="text/javascript">
var str = "<?php echo $str ?>"; // error: missing ; before statement
var long_str = "<?php echo $long_str ?>";
// error: unterminated string literal
</script>

You can use json_encode to escape (i.e., place a \ before) the problem characters and eliminate the JavaScript errors:

<script type="text/javascript">
var str = <?php echo json_encode($str) ?>; // "A \"string\" here"
var long_str = <?php echo json_encode($long_str) ?>;
// "A longer string\n     with a line break"
</script>

Even though json_encode is able to resolve problems in these example strings, it may be better to handle problem characters up front, as another example demonstrates.

Back to top