如何在PHP中添加javascript代码? [重复]

This question already has an answer here:

I want to add script code in php but it giving error on this line

$a=echo "document.getElementById('t1').value;";

of unexpected use of ECHO! Can any one help???

<?php
    echo "<script>";
    $a=echo "document.getElementById('t1').value;";


    if($_session['user']==$a) {
        echo 'function fun() {
            document.write("welcom");
        }';
    }

    echo "</script>";
?>
</div>

You cant use echo function in variable. You can echo variable only and there are 2 ways, how to achieve this:

1) you can save the content into variable via:

$a = "document.getElementById('t1').value;"; 

and somewhere in your code where you will need it you can echo the content of $a variable via: echo $a;

2) you can echo the content of your variable in the concrete line:

echo "document.getElementById('t1').value;";

Your problem is from $a=echo because echo is a php function.

The correct syntax is:

<?php
$a= "document.getElementById('t1').value;";
echo "<script>";
echo $a;
if($_session['user']==$a) {
    echo 'document.write("welcom");';
}
echo "</script>";
?>