ilyketurdles
ilyketurdles

Reputation: 113

Using PHP variable inside HTML, in a PHP file

I've been trying to get this to work for a while now, and have yet to find a solution online that works. I'm still fairly new to PHP so forgive me if the question is dumb.

I'm using a PHP document to read data from a text file. That PHP document is called as a script to the HTML document which actually displays all the information on the webpage.

So to my understanding, I have to use echo "document.write("")"; to output stuff, which works fine.

However, when I try using variables, it doesn't seem to work. For example I'm trying to do:

<?php 
$test = "Hello";
echo "document.write("$test")" ?>

Am I missing something?

Upvotes: 0

Views: 141

Answers (8)

Raghbendra Nayak
Raghbendra Nayak

Reputation: 1646

If you want output into HTML then you can simply use echo function of PHP.

<?php 
$test = "Hello";
echo "<script>document.write('" .$test ."')</script>";
?>

Upvotes: 0

Uours
Uours

Reputation: 2492

I think you need quotes around the string in the document.write :

<script>
<?php
    $test = "Hello";
    echo "document.write('" .$test ."');";
?>
</script>

Which becomes :

<script>
document.write('Hello');
</script>

Which in turn displays this on the page :

Hello

Upvotes: 0

user1864610
user1864610

Reputation:

The specific reason your code is not working is your use of quotes. You can't enclose double-quotes within double quotes unless you escape them first - like this:

echo "document.write(\"$test\")" ?>

However, there is a deeper problem here. You don't need the Javascript at all. You could just do:

echo $test;

Lastly, document.write() has all sorts of unwanted side effects. If really do need that then you probably want to manipulate the DOM in Javascript directly, but that's a different question.

Upvotes: 3

Navneil Naicker
Navneil Naicker

Reputation: 3691

I don't what you are trying to do, if you want to just output a text into a php usse echo

Your wrote it's incorrect

<?php 
    $test = "Hello";
    echo "document.write("$test")";
?>

Correct way

<?php 
    $test = "Hello";
    echo $test;
?>

Upvotes: 0

saurabh kumar
saurabh kumar

Reputation: 164

because document.write(); is for javascript,to use variable just use variable name only in echo

Upvotes: 0

EyasSH
EyasSH

Reputation: 3769

If you want document.write to add the value of the $test variable in JavaScript, you are almost on the right track, but need to escape your quotation marks:

echo "document.write(\"$test\")";

Upvotes: 0

Guy P
Guy P

Reputation: 1423

document.write only works in JavaScript, try just use echo

Upvotes: 0

Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

Just use echo to do what you want:

<?php 
$test = "Hello";
echo $test; 
?>

Value of $test will be outputted to the html.

Upvotes: 0

Related Questions