Does json_encode add additional quotes?
http://codepad.org/zmsXbqhu
I have very simple code (viewable above):
<?php
$js = json_encode( "HO" );
var_dump( $js );
?>
It returns a st开发者_开发知识库ring with extra quotes around it:
string(4) ""HO""
Any idea why that is?
Because you are var_dump'ing. It wraps it in the quotes. If you don't var_dump and echo you will see the actual string.
Here, take a look at this:
http://codepad.viper-7.com/KB5Fkk
Code
<?php
$js = json_encode( '{ book : "how to use json", author: "some clever guy" }' );
var_dump( $js );
echo "<br /> The actual string:<br />";
echo $js;
?>
Output:
string(61) ""{ book : \"how to use json\", author: \"some clever guy\" }""
The actual string:
"{ book : \"how to use json\", author: \"some clever guy\" }"
In JSON...
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.
source
If you do it like that:
$json = json_encode("HO");
echo $json;
it will return the following:
"HO"
The reason your code returns something like that:
string(4) ""HO""
is that you used var_dump()
, which can not be treaten as echo
's replacement (see var_dump() documentation).
精彩评论