How can JSON be used to handle PHP variables in JavaScript?

To handle PHP variables in JavaScript, you can encode the PHP variables into JSON format using the json_encode function in PHP. Then, you can output this JSON data within a script tag in your HTML document. In your JavaScript code, you can parse this JSON data using the JSON.parse function to access the PHP variables as JavaScript objects.

<?php
$phpVariable = "Hello, World!";
$encodedData = json_encode($phpVariable);
?>

<script>
var jsonData = <?php echo $encodedData; ?>;
var jsVariable = JSON.parse(jsonData);
console.log(jsVariable);
</script>