What are the best practices for handling JavaScript code within PHP for opening popup windows?

When handling JavaScript code within PHP for opening popup windows, it is best practice to properly escape the JavaScript code to prevent any syntax errors or security vulnerabilities. One way to achieve this is by using the json_encode function in PHP to encode the JavaScript code as a JSON string, which can then be safely embedded within the HTML output.

<?php
$popupScript = 'alert("This is a popup window");';
$escapedPopupScript = json_encode($popupScript);
echo '<script type="text/javascript">eval(' . $escapedPopupScript . ')</script>';
?>