[php] PHP JSON String, escape Double Quotes for JS output

I'm creating a JSON string from a PHP array. I've encoded it using json_encode().

$data = array(
    'title' => 'Example string\'s with "special" characters'
);

$data = json_encode( $data );

$data is localized using wp_localize_script() and is accessible via a global data variable.

In the JS file I can access the information by the following:

var data     = data.replace( /"/g, '"' ),
    jsonData = jQuery.parseJSON( data );

console.log( jsonData );

This results in an output of:

{ "title":"Example string's with "special" characters" }

Entering that result into http://jsonlint.com/ returns an error. Removing the double quotes around "special" validates the string.

What is the best way to create a JSON string from PHP and properly escape it for use in a JS file?

This question is related to php escaping json double-quotes

The answer is


I just ran into this problem and the actual issue was that I forgot to add a proper application/json header before spitting out the actual JSON data.

header('Content-Type: application/json');

This is a solutions that takes care of single and double quotes:

<?php
$php_data = array("title"=>"Example string's with \"special\" characters");

$escaped_data = json_encode( $php_data, JSON_HEX_QUOT|JSON_HEX_APOS );
$escaped_data = str_replace("\u0022", "\\\"", $escaped_data );
$escaped_data = str_replace("\u0027", "\\'",  $escaped_data );
?>
<script>
// no need to use JSON.parse()...
var js_data = <?= $escaped_data ?>;
alert(js_data.title); // should alert `Example string's with "special" characters`
</script>

Another way would be to encode the quotes using htmlspecialchars:

$json_array = array(
    'title' => 'Example string\'s with "special" characters'
);

$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');

I succefully just did this :

$json = str_replace("\u0022","\\\\\"",json_encode( $phpArray,JSON_HEX_QUOT)); 

json_encode() by default will escape " to \" . But it's still wrong JSON for json.PARSE(). So by adding option JSON_HEX_QUOT, json_encode() will replace " with \u0022. json.PARSE() still will not like \u0022. So then we need to replace \u0022 with \\". The \\\\\" is escaped \\".

NOTE : you can add option JSON_HEX_APOS to replace single quote with unicode HEX value if you have javascript single quote issue.

ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));


I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around

$products = array($ofDirtyArray);
if($products !=null) {
    header("Content-type: application/json");
    header('Content-Type: charset=utf-8');
    array_walk_recursive($products, function(&$val) {
        $val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
    });
    echo json_encode($products,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}

I hope it helps someone/someone improves it.


Use json_encode($json_array, JSON_HEX_QUOT); since php 5.3: http://php.net/manual/en/json.constants.php


Error come on script not in HTML tags.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php print_r($_POST??'') ?></pre>

<form method="POST">
    <input type="text" name="name"><br>
    <input type="email" name="email"><br>
    <input type="time" name="time"><br>
    <input type="date" name="date"><br>
    <input type="hidden" name="id"><br>
    <textarea name="detail"></textarea>
    <input type="submit" value="Submit"><br>
</form>
<?php 
/* data */
$data = [
            'name'=>'loKESH"'."'\\\\",
            'email'=>'[email protected]',
            'time'=>date('H:i:00'),
            'date'=>date('Y-m-d'),
            'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\    ",
            'id'=>123,
        ];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($_POST??$data)?></span>
<script type="text/javascript">
    /* Error */
    // var json = JSON.parse('<?=json_encode($data)?>');
    /* Error solved */
    var json = JSON.parse($('.ajax-data').html());
    console.log(json)
    /* automatically assigned value by name attr */
    for(x in json){
        $('[name="'+x+'"]').val(json[x]);
    }
</script>

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to escaping

Uses for the '&quot;' entity in HTML Javascript - How to show escape characters in a string? How to print a single backslash? How to escape special characters of a string with single backslashes Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence Properly escape a double quote in CSV How to Git stash pop specific stash in 1.8.3? In Java, should I escape a single quotation mark (') in String (double quoted)? How do I escape a single quote ( ' ) in JavaScript? Which characters need to be escaped when using Bash?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to double-quotes

Adding double quote delimiters into csv file Add php variable inside echo statement as href link address? Calling one Bash script from another Script passing it arguments with quotes and spaces Escape double quotes in a string How do I put double quotes in a string in vba? PHP JSON String, escape Double Quotes for JS output How to add double quotes to a string that is inside a variable? How can I make Java print quotes, like "Hello"? How to include quotes in a string