Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

escaping - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...