View Full Version : Using PHP to output a JS code for <script> tag

08-09-2007, 03:18 PM

This one should be simple I guess. I'm quite newbie with PHP, that's why asking.

I'd like to build a script that outputs JS code that can be used within a <script> tag.

For example:

<script type="text/javascript" language="javascript" src="http://mydomain.com/widgetscript.php?v=param1"></script>

So the JS source is returned from the PHP script, according to the desired parameters.

08-09-2007, 03:26 PM
Just echo it out like you would with HTML:

echo('<script type="text/javascript" language="javascript" src="http://mydomain.com/widgetscript.php?v=param1"></script>');

Then echo out the JS in the PHP file you're src'ing according to taste.


08-09-2007, 05:37 PM
Hi Dan, thanks.

yup, it works. Now I have another icky problem.
I'm echoing rather a big HTML chunk, and apparently it isn't output at all.

When I truncated it to 4-5 lines, it does get echoed ok.

So I guess it might be a problem of the string length that is passed to the 'echo' function?

should I create a string var instead?

08-09-2007, 05:50 PM
I'm, a newbie to this to so i may be totaly wrong, But perhaps using the heredoc syntax as suppose to echo will work better in your case. heredocs are good when u have a large amount if text to output. check out http://ca.php.net/types.string and scroll down a bit to where they talk about heredocs.

*Any php guru's out there don't feel bad to bash my solution if it is wrong. haha

08-10-2007, 02:12 AM
Simply escaping out of PHP to specify it as plain HTML might be easier.

08-10-2007, 11:02 AM
instead of echoing a large chunk of items why not do this


$num = rand(1, 20);
if($num > 10) {
<div id="option1">
hi this will only appear if $num is greater than 10!
<?php }
else {
<div id="option2">
hello, this will only appear if $num is less than or equal to 10
<?php } ?>

you might find it strange to keep closing and opening php tags, but truth is the page will load slower if you rely on php to echo everything. this way there won't be any problems with echos especially if you have forgotten to backslash something out and the page will load quicker.