Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Echoing JSON string into HTML Input value - Need character escape

Here is a simplified version of my code that I am having a problem with.

$variable = "{\\\"JSON" //long JSON string created in Javascript with JSON.stringify
?> <input type="text" name="somename" value="<?php echo $variable; ?>"/> <?php

The input box only contains {\ I need a way to escape the entire JSON string

Thanks Alex

like image 283
Alex Avatar asked Feb 19 '14 16:02

Alex


1 Answers

You're outputting into an HTML context, so you need html-specific escaping:

<input ... value="<?php echo htmlspecialchars(json_encode($whatever)); ?>" />
                             ^^^^^^^^^^^^^^^^----
like image 182
Marc B Avatar answered Oct 04 '22 02:10

Marc B