I convert the array into a JSON string into PHP :

 $str = json_encode(['key' => 'value']); 

Then I write the converted string in the data attribute of the HTML markup element. It turns out like this:

 <span data-param = "{"key": "value"}">...</span> 

Excited by the fact that there are double quotes inside the attribute description, but the reading and the inverse transformation ( json_decode ) occur normally and the markup does not collapse. Will there be further problems with such markup and, if there are possible problems, how to avoid them?

  • one
    In general, according to the standard, keys and strings in JSON should be in double quotes - rjhdby

1 answer 1

Use a pair of htmlspecialchars / htmlspecialchars_decode

 <div data-json="<?=htmlspecialchars($json)?>"></div> 

And later:

 $data = json_decode(htmlspecialchars_decode($dataJson), true); 

Where $dataJson is the content of the attribute (transferred via ajax, for example)