How can PHP variables be properly inserted into JavaScript strings to avoid syntax errors?

When inserting PHP variables into JavaScript strings, it's important to properly escape the variables to avoid syntax errors. One way to do this is by using PHP's json_encode function to convert the PHP variable into a JSON string, which can then be safely inserted into the JavaScript code.

<?php
$php_variable = "Hello, world!";
?>
<script>
var js_variable = <?php echo json_encode($php_variable); ?>;
console.log(js_variable);
</script>