Suppose I have a PHP script that returns a json response. It looks something like this:
$ctype = ContentNego::desiredContentType();
header("Content-Type: $ctype");
if (ContentNego::flavor($ctype) == ContentFlavor::JSON) {
echo '{ "name": "' . $name . '", ' .
'"comment": "' . $comment . '"}';
}
.... other content types here....
Prior to the code above, I have
class ContentFlavor {
const XML = 1;
const JSON = 2;
const TEXT = 3;
const Unknown = 4;
}
And the value of $cftype is set by examining the incoming Accept header, in a basic form of content-type negotiation.
The string echoed by the php script looks like this:
[ "name" : "Vettel", "comment" : "He's terrific" ]
In the browser, I have javascript like this:
$.ajax({type: "GET",
url: url,
dataType: "json",
headers : { "Accept" : 'application/json' },
cache: false,
error: function (xhr, textStatus, errorThrown) {
enableEditboxButtons();
},
success: function (data, textStatus, xhr) {
// fill and show the editbox dialog
...
}});
But when I receive this content on the jQuery side, I get this:
[ "name" : "Vettel", "comment" : "He\'s terrific" ]
Notice the injected backslash “escaping” the apostrophe or single-quote. My code did not put that backslash there. It seems to have been injected by PHP? Also it seems to be against the requirements of JSON encoding as stipulated on http://json.org:

The resulting json string with the escaped apostrophe fails to parse in jQuery 1.7.1, and my error fn gets called.
What’s the deal? Is PHP really doing this escaping, and if so why/how? (It runs on PHP 5.2.17 on Linux) Can I avoid it?
If not, how can I work around this problem?
Cheeso, make sure the *magic_quotes_gpc* and *magic_quotes_runtime* option is turned off on the PHP configuration (that could be putting the backslash there, more info here).
Also you probably should use the json_encode method if you can, it makes life a lot easier as you can pass an array or object directly to it and get a JSON version of the represented data.