How can I put double quotes inside a string within an ajax JSON response from php?

How can I put double quotes inside a string within an ajax JSON response from php?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Double Quotes in PHP JSON Responses

Embedding literal double quotes inside a string value within a JSON payload is a classic source of confusion. When you attempt to send data like hello "kitty" from a PHP backend to a JavaScript frontend via AJAX, the resulting parse error usually stems from a misunderstanding of how JSON formatting interacts with string delimiters. The core challenge lies in distinguishing between the characters that define the end of a string and the characters that are part of the string content itself.

In JSON, double quotes (") serve a dual purpose: they wrap strings to indicate their boundaries, and they represent literal text inside those strings. To store a literal quote character within a string, you must escape it using a backslash. The resulting sequence \ followed by " tells the JSON parser to treat that specific quote as data rather than a terminator.

The source material highlights a common stumbling block where developers attempt to manually manipulate the string in PHP before echoing it. A frequent mistake is converting quotes to the character entity \x22. While this works in HTML contexts, JavaScript's JSON.parse() method expects standard JSON escaping sequences, not hexadecimal escape codes within the raw JSON text stream. When the server outputs { "b" : "hello \x22kitty\"" }, the client-side parser fails because it encounters unexpected characters or incorrect syntax for a string literal.

The confusion often arises when developers mix up how echo renders strings versus how those strings are interpreted by a JSON parser. Consider the PHP code snippet provided in the source material:

$b = 'hello "kitty"';      
// $b = str_replace('"',"\x22",$b); // Incorrect for JSON
// $b = addslashes($b);              // Unsafe and non-standard for JSON
$b = str_replace('"','\"',$b);      // Often misunderstood behavior
echo '{ "a" : "1", "b" : "' . $b . '"}';

If you execute this code, the output sent to the browser will look like this:
{ "a" : "1", "b" : "hello \"kitty\"" }

At first glance, this looks correct. However, if you inspect the raw bytes or try to parse it programmatically without careful attention to how PHP's echo handles backslashes, issues arise. The problem is that PHP treats a single backslash in a double-quoted string as an escape character. If you want the output to literally contain a backslash followed by a quote, you must use two backslashes in your PHP string:

$b = 'hello "kitty"';      
$b = str_replace('"','\\"',$b); 
echo '{ "a" : "1", "b" : "' . $b . '"}';

This results in the output: { "a" : "1", "b" : "hello \"kitty\"" }. Now, when JavaScript receives this payload and runs JSON.parse(), it successfully interprets \" as a literal double quote character. The string value stored in the object becomes hello "kitty" exactly as intended.

It is crucial to avoid using functions like addslashes() for JSON generation. addslashes() adds backslashes before single quotes, double quotes, and newlines. In JSON, you only need to escape double quotes (and specific control characters). Adding a slash before a single quote creates invalid JSON syntax, leading to parse errors on the client side.

The most robust solution, which avoids manual string manipulation entirely, is to leverage PHP's built-in json_encode() function. This function handles all necessary escaping automatically according to the JSON specification:

$data = [
    "a" => "1", 
    "b" => 'hello "kitty"'
];

$json = json_encode($data);
echo $json;
// Output: {"a":"1","b":"hello \"kitty\""}

Using json_encode() ensures that the resulting string is valid JSON regardless of the complexity of the data. It also handles special characters like newlines, tabs, and backslashes correctly. If you are using Laravel, this pattern aligns with how the framework expects data to be structured before sending it in an API response. For further reading on building APIs in PHP, you might explore resources from https://laravelcompany.com.

Attempting to manually construct JSON strings by concatenating variables is generally discouraged unless absolutely necessary. It invites errors where developers forget to escape specific characters or misinterpret how the language handles backslashes. By relying on json_encode() or ensuring that manual replacements use double backslashes (\\) before a quote, you guarantee that the client receives a valid JSON object that parses cleanly into JavaScript data structures.

Our network