Simpe method to use JavaScript inside PHP without all the messy code is a global function:
function js_link($src)
{
//set root path to scripts folder
if(file_exists("my/html/root/" . $src))
{
//we know it will exists within the HTTP Context
return sprintf("<script type="text/javascript" src="%s"></script>",$src);
}
return "<!-- Unable to load " . $src . "-->";
}
Then use:
echo js_link("folder/to/yourscript.js");