What are the best practices for handling data attributes in HTML elements when passing data from PHP to JavaScript in PHP applications?

When passing data from PHP to JavaScript in PHP applications, one of the best practices is to use data attributes in HTML elements to store the data. This allows for easy access to the data in JavaScript without the need for inline scripts or global variables. By setting data attributes in the HTML elements using PHP, the data can be dynamically generated and accessed in JavaScript.

<?php
// PHP code to set data attributes in HTML elements
$data = "Hello, World!"; // Data to pass from PHP to JavaScript

echo '<div id="myElement" data-mydata="' . htmlspecialchars($data) . '"></div>';
?>