Skip to content Skip to sidebar Skip to footer

Php Variable Inside Echo 'html Code'

I have php file index.php In this file to use html code I am doing: index.php echo '
'; In href I want to put value of so

Solution 1:

You concatenate the string by ending it and starting it again:

echo '
<div><aclass="fragment"href="' . $url . '"><div>';

Though I personally prefer to stop the PHP tags and start them again (if I have a lot of HTML) as my IDE won't syntax highlight the HTML as it's a string:

?>
    <div><aclass="fragment"href="<?phpecho$url; ?>">link</a></div><?php

Solution 2:

Since you are printing several lines of HTML, I would suggest using a heredoc as such:

echo <<<HTML
<div><aclass="fragment"href="$url"><div>
HTML;

HTML can be anything as long as you use the same tag both in the beginning and the end. The end tag must however be on its own line without any spaces or tabs. With that said, specifically HTML also has the benefit that some editors (e.g. VIM) recognise it and apply HTML syntax colouring on the text instead of merely coluring it like a regular string.

If you want to use arrays or similar you can escape the variable with {} as such:

echo <<<HTML
<div>{$someArray[1]}</div>
HTML;

Solution 3:

if you are echoing php directly into html i like to do this

<div><?=$variable?></div>

much shorter than writing the whole thing out (php echo blah blah)

if you are writing html in php directly then there several options

$var = '<div>'.$variable.'</div>';   // concatenate the string$var = "<div>$variable</div>";       // let php parse it for you.  requires double quotes$var = "<div>{$variable}</div>";     // separate variable with curly braces, also requires double quotes

Solution 4:

Do it like

<?php$url='http://www.stackoverflow.com';
echo"<div><a class='fragment' href='$url' /></div>";

Solution 5:

If you want to maintain the echo statement you can do either

echo'<a class="fragment" href="'.$url.'"><div>';

or

echo "<a class=\"fragment\" href=\"$url\">";

The first is better for performances and IMHO is more readable as well.

Post a Comment for "Php Variable Inside Echo 'html Code'"