How can potential syntax errors, like unexpected strings, be avoided when outputting HTML and Javascript in PHP?

To avoid potential syntax errors like unexpected strings when outputting HTML and JavaScript in PHP, you can use a combination of concatenation and escaping characters. This involves breaking up your output into smaller parts and concatenating them together using the "." operator. Additionally, you can use functions like htmlspecialchars() to escape special characters in your output.

<?php
// Example of outputting HTML and JavaScript safely in PHP
$name = "John";
$age = 25;

echo "<p>Hello, " . htmlspecialchars($name) . "</p>";
echo "<script>var age = " . $age . ";</script>";
?>