I don't know if it's considered bad practice, or if it's the way everyone does it, but I find myself inserting JSON data into HTML element attributes all the time. So, for instance:
Now I know that json_encode has options like JSON_HEX_APOS and JSON_HEX_QUOT, but I also want to use html_escape() which is why I'm using str_replace the way I am. This allows me to do this:
Then later in my json I can use JSON.parse() on the contents of that data-json attribute.
What are your thoughts here? Is there a better way?
PHP Code:
foreach( $query->result_array() as $row )
$arr[] = (object) array_map( 'html_escape', $row );
$json = json_encode( $arr );
$json_string = str_replace([
'"',
''',
'& #039;' // space here for codeigniter forum
], [
'\u0022',
'\u0027',
'\u0027'
], $json );
Now I know that json_encode has options like JSON_HEX_APOS and JSON_HEX_QUOT, but I also want to use html_escape() which is why I'm using str_replace the way I am. This allows me to do this:
PHP Code:
echo '<div data-json=\'' . $json_string . '\'>';
Then later in my json I can use JSON.parse() on the contents of that data-json attribute.
What are your thoughts here? Is there a better way?