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>
CodePudding user response:
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.
CodePudding user response:
but it returns JavaScript object not a Json string
You skip a few steps here:
json_encode
returns a string in PHP- That string is given to the
echo
statement - Everything that is output, is passed as the HTML page for the browser to interpret
- The browser uses its JavaScript engine to parse the scripts that are part of the page -- that JSON is parsed as any other object literal that might occur in the script.
- To the JavaScript engine, this part of the script is not a string, but an object literal.
It 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.