php-n00b Posted April 12, 2010 Share Posted April 12, 2010 What's Up? OK, So I'm using the IF and ELSE function to echo some html code, But I need to be able to echo the contents of a variable inside of some html code. if ($var1=="text") echo '<body><text>$text</text></body>' else echo 'Failed' But of course instead of echoing the contents of the $text variable, It just echo $text. I'ved tried putting. if ($var1=="text") echo '<body><text>'; echo $text; echo '</text></body>' else echo 'Failed' But I got another error, Someone in IRC mentioned the word backslash, However that was the only advice I got. Thanks Bye! Link to comment https://forums.phpfreaks.com/topic/198301-variable-inside-of-html/ Share on other sites More sharing options...
Ken2k7 Posted April 12, 2010 Share Posted April 12, 2010 Before I start, you are required to end statements with semi-colons in PHP. Also, is <text> really a HTML tag? I prefer not making stuff up. There are a few ways to do that. 1. Variable interpolation 2. String concatenation 3. String formatting 1. For variable interpolation, like you had in your first example, you can only do that with double quotes. So if you change those single quotes to double quotes, it should work. 2. String concatenations are done via the . (dot) operator. Example: echo '<body>' . $text . '</body>'; 3. String formatting is done via a few of PHP functions. sprintf and printf comes to mind. Example: echo sprintf('<body>%s</body>', $text); I usually prefer the last method because it looks cleaner. Link to comment https://forums.phpfreaks.com/topic/198301-variable-inside-of-html/#findComment-1040460 Share on other sites More sharing options...
teamatomic Posted April 12, 2010 Share Posted April 12, 2010 Change the single quotes: echo '<body><text>$text</text></body>'; to double quotes: echo "<body><text>$text</text></body>"; Then if $text has a value it will be echoed. HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/198301-variable-inside-of-html/#findComment-1040471 Share on other sites More sharing options...
litebearer Posted April 12, 2010 Share Posted April 12, 2010 of course there is also 'dropping" in and out of php... <?PHP //some php code ?> <body> some html stuff <?PHP echo $somevariable; ?> // more html stuff </body> Link to comment https://forums.phpfreaks.com/topic/198301-variable-inside-of-html/#findComment-1040472 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.