PHP json_encode
Returns a string containing the JSON representation of the supplied value. php.net
but it returns JavaScript object not a Json string:
<script>
var app = <?php echo json_encode($array); ?>;
alert(app.name)
</script>
but it returns JavaScript object not a Json string:
Context matters, consider this code:
<?php
$array = ['name' => 'John Doe'];
$string = json_encode($array);
var_dump($string);
Executing that produces:
$ php index.php
string(19) "{"name":"John Doe"}"
string(19) means the variable is a string of 19 characters. The fact that string can be interpretted by js as an object is immaterial here, to php it is producing a string.
but it returns JavaScript object not a Json string
You skip a few steps here:
json_encode returns a string in PHPecho statementIt may help to rewrite the PHP script to something that is equivalent:
echo "
<script>
var app = " . json_encode($array) . ";
alert(app.name)
</script>";
So now it is clear that PHP sends one string, which happens to represent valid JavaScript -- enclosed in a <script> tag. The JSON is just a part of that long string, which later the browser will parse, and where the JavaScript part is parsed by a JavaScript engine.