The function json_encode
converts objects and arrays into a JSON string, but it makes no sense to convert a normal string into JSON, i.e.:
$foo = array(
'bar' => 'Olá',
'baz' => 'Mundo!'
);
echo json_encode($foo);
It will turn this (which is a valid json):
{"bar":"Ol\u00e1","baz":"Mundo!"}
And this:
$foo = array( 'Olá', 'Mundo!' );
echo json_encode($foo);
You will flip this (which is an indexed/iterable valid json):
["Ol\u00e1","Mundo!"]
Now this:
echo json_encode('Olá mundo!');
Or this:
echo json_encode("Olá mundo!");
It will only escape the string where it has accents and apply the quotes:
"Ol\u00e1 mundo!"
In other words, this is not a JSON, it is just a string that can be used with JSON, or other functions for Javascript
Read about the exhaust: Writing PHP code without special characters
Note: if the document is not saved in a Unicode format, such as utf8, json_encode
will not work, will return the value NULL
read more about using utf-8 on your PHP pages: Doubt with charset=iso-8859-1 and utf8
The use of json_encode
with strings is allowed because the same escape that is used for JSON is used for Javascript, since JSON is an accepted and widely used format with JS. Even the use of HTML attributes called data-*
can make use of this escape.
An example of using json_encode
with strings would create a function generated via PHP that will run on JS, for example if you create a file like this:
foo.php
<?php
echo 'foo(' . json_encode('teste') . ')';
And call him that on another HTML page:
<script src="foo.php"></script>
The script (and function) would be processed and downloaded like this in the browser:
foo("teste");
Of course you could do this directly/manually, without needing to json_encode
, but imagine that the string has broken lines or quotes, if you do this:
$arg = '
olá mundo
"isso é um teste"
';
echo 'foo("' . $arg . '")';
Will generate this:
foo("
olá mundo
"isso é um teste"
");
Which will give syntax error when running in Javascript, due to line breaks and "quotation marks" "inside quotation marks", but if used json_encode
$arg = '
olá mundo
"isso é um teste"
';
echo 'foo(' . json_encode($arg) . ')';
It will escape the accents, breaks of lines and quotes, getting like this:
foo("\n ol\u00e1 mundo\n\n \"isso \u00e9 um teste\"\n ")
What will run correctly in Javascript.
is because the
json_encode
does the encoding of arrays, it is identifying "test" as key and no value, ie NULL value– Wees Smith
So... I had done tests with a simple 'echo "test"' too, but the result is the same. I had the idea to change dataType to "html" and return only one php string, but the word NULL keeps appearing.
– Marlon Souza