What are the best practices for handling PHP output within JavaScript functions?

When handling PHP output within JavaScript functions, it is important to properly encode the PHP data to prevent any potential security vulnerabilities such as XSS attacks. One common method to achieve this is by using JSON encoding to safely pass PHP data to JavaScript functions. This ensures that the data is properly formatted and secure for use in client-side scripts.

<?php
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
);

echo '<script>';
echo 'var jsonData = ' . json_encode($data) . ';';
echo '</script>';
?>