You have to "write to the browser". Remember anything you output to a page goes to the browser (unless its command line).
Eg:
<?php
echo "<script>function foo() { alert('bar'); }</script>";
?>
will output the javascript.
If you have problems dealing with " and ' (as javascript frequently uses both, and escaping can be a pain) use:
echo EOT<<<
<script>
function foo() {
alert("bar");
}
</script>
EOT;
You don't need to escape anything.
Just note that the EOT; must be located on a new line, with no tabs/spaces before it (in column 1) Enjoy.