user123
user123

Reputation: 5407

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 '
<div>
<a class="fragment" href="">
<div>';

In href I want to put value of some php variable i.e. $url How could be done?

is this correct way?

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

Upvotes: 2

Views: 22102

Answers (6)

Daniel Perv&#225;n
Daniel Perv&#225;n

Reputation: 1716

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

echo <<<HTML
<div>
<a class="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;

Upvotes: 6

Do it like

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

Upvotes: 2

Sammitch
Sammitch

Reputation: 32272

If you want to input/output large blocks of HTML with embedded variables you can simplify the process by using Heredocs:

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

You don't have to worry about escaping quotes, constant concatenation, or that ugly dropping in and out of <?php echo $var; ?> that people do.

Upvotes: 1

hamobi
hamobi

Reputation: 8130

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

Upvotes: 5

Eugenio
Eugenio

Reputation: 3445

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.

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39550

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

echo '
<div>
<a class="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>
        <a class="fragment" href="<?php echo $url; ?>">link</a>
    </div>
<?php

Upvotes: 11

Related Questions