How to print a JSON string within an input with PHP?

3

I need to print a string JSON from PHP within value of a input , to then be able to recover it with JavaScript .

<?php
    $array = array(
        "foo" => "bar",
    );
    $json = json_encode($array);
?>

<input id="input" value="<?php echo $json; ?>" />

<script>
  let json = JSON.parse(document.getElementById('input').value);
  console.log(json);
</script>

What would I have to do to print the JSON and then be able to recover it from JavaScript ?

    
asked by Marcos 24.08.2017 в 21:34
source

1 answer

2

What is needed is to escape the characters HTML to prevent it from breaking when printing the JSON . PHP has the function htmlspecialchars which:

  

Convert special characters to HTML entities

Solution:

<?php
    $array = array(
        "foo" => "bar",
    );
    $json = json_encode($array);
?>

<!-- Usamos "htmlspecialchars" para encodear el JSON -->
<input id="input" value="<?php echo htmlspecialchars($json); ?>" />

<script>
  let json = JSON.parse(document.getElementById('input').value);
  console.log(json);
</script>
    
answered by 24.08.2017 в 21:34