If all you want is to pass some data to JavaScript, why not just write it directly to a variable:
<html>
<head>
<script>
var data = <?php echo json_encode($data); ?>
</script>
<!-- etc. -->
Anyway, if you want to do it your way, you can use htmlspecialchars
to escape arbitrary data before putting it in an HTML attribute:
<div data="<?php echo htmlspecialchars('"\'!)(@UI#_!)(@JP_!()@J'); ?>">Example</div>
If you then read that with JavaScript, it should understand the HTML encoding, so you won't need to do anything special to read it.
If your data is more complex, but not binary, you could JSON encode it, then use htmlspecialchars
:
<?php
$data = array();
$data["a"] = 123;
$data["b"] = "example";
$jsonData = json_encode($data);
$escapedJsonData = htmlspecialchars($jsonData);
echo "<div data=\"$escapedJsonData\">example</div>";
?>
You can then read that data in JavaScript using JSON.parse:
var yourDiv = getDivSomehow();
var data = JSON.parse(yourDiv.getAttribute("data"));
If your data is binary, you can base64 encode it:
<?php
$data = someImage();
$encodedData = base64_encode($data);
echo "<div data=\"$encodedData\">example</div>";
?>
Presumably there's some way to decode this in JavaScript.