php variable inside echo 'html code' - php

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; ?>">

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

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;

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

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

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.

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.

Related

Getting string for database and use it as img src

I have problem looping out pictures from a database.
I have no problem getting the information(string) that I need from the database. The problems accure when I try to use the string as a img src-tag.
My code:
<?php
foreach ($console as $con):
echo '<li>', $con['brand'], ', ',$con['pic'], '</li>';
echo'<div class="item2">
<a href="xboxconsol.html">
<img src=',$con['pic'],'/>
</a>
</div>';
endforeach;
?>
Note, the li-elements put out the correct information but when I use it in the img-tag it adds a "/" at the end on the string.
Example of list output:
Playstation, ../playstation.jpg
The picutre however output the URL to the pic as:
../playstation.jpg/
Where do the last "/" come from and how do I get rid of it?
You need to quote the attribute value.
echo'<div class="item2">
<a href="xboxconsol.html">
<img src="',$con['pic'],'"/>
</a>
</div>';
Currently the browser is guessing what the attribute should contain.
Which comes out as:
<img src="value/">
but you want:
<img src="value"/>
You need to quote your concatenations, be very careful how you output HTML from PHP.
I'd rather concatenate the variables like this instead:
foreach ($console as $con)
{
echo "<li>{$con['brand']} {$con['pic']}</li>";
echo "<div class='item2'>
<a href='xboxconsol.html'>
<img src=\"{$con['pic']}\" />
</a>
</div>";
}
It's way cleaner and more readable.

PHP echo inside echo

I'm trying to call an HTML/PHP content that it's inside my database using:
<?php echo $row_content['conteudo']; ?>
When the row is called the HTML appears correctly but the PHP doesn't.
I belieave it's cause of the echo inside the main echo.
<?php echo "
<h3>Hello</h3>
<?php do { ?>
<div class=\"indios\">
<a href=\"indio.php?id=<?php echo $row_indiosct['id']; ?>\">
<img src=\"galeria/indios/<?php echo $row_indiosct['foto']; ?>\" alt=\"<?php echo $row_indiosct['nome']; ?>\" />
<br /><?php echo $row_indiosct['nome']; ?></a></div>
<?php } while ($row_indiosct = mysql_fetch_assoc($indiosct)); ?> "
?>
The line one of this code is the same echo as the first code field, it's not repeating, it's there just for help and to understand where is the problem.
I already fixed some quotation marks but it gives an error in the line of the 1st echo.
That is some of the ugliest code I have ever seen...
<?php
echo '
<h3>Hello</h3>';
while ($row_indiosct = mysql_fetch_assoc($indiosct))
{
echo '
<div class="indios">
<a href="indio.php?id='.$row_indiosct['id'].'">
<img src="galeria/indios/'. $row_indiosct['foto'].'" alt="'.$row_indiosct['nome'].'" />
<br />'.$row_indiosct['nome'].'</a>
</div>';
}
?>
You could also use the HEREDOC syntax.
Don't do this. Multi-line echoes, especially when you've got embedded quotes, quickly become a pain. Use a HEREDOC instead.
<?php
echo <<<EOL
<h3>Hello</h3>
...
<div class"indios">
...
EOL;
and yes, the PHP inside your echo will NOT execute. PHP is not a "recursively executable" language. If you're outputting a string, any php code embedded in that string is not executed - it'll be treated as part of the output, e.g.
echo "<?php echo 'foo' ?>"
is NOT going to output just foo. You'll actually get as output
<?php echo 'foo' ?>
You have misunderstood how PHP works. PHP is processed by the server. When it encounters your script, it sees the following:
<?php echo "some long piece of text that you have told PHP not to look at" ?>
What is the reasoning behind trying to nest PHP calls inside strings?
evaluate code php in string using the function eval(): this post Execute PHP code in a string
<?php
$motto = 'Hello';
$str = '<h1>Welcome</h1><?php echo $motto?><br/>';
eval("?> $str <?php ");
http://codepad.org/ao2PPHN7
also if your need the code buffer output in a string also you can using the ob_start() method:
<?php ob_start(); ?>
<h3>Hello</h3>;
<?php
while ($row_indiosct = mysql_fetch_assoc($indiosct)){ ?>
<div class="indios">
<a href="indio.php?id='<?php echo $row_indiosct['id']'">
<img src="galeria/indios/'<?php echo $row_indiosct['foto'].'" alt="'.$row_indiosct['nome'].'" />
<br />'.$row_indiosct['nome'].'</a>
</div>';
<?php } ?>

Echoing javascript with events and function calls with parameters in PHP

I want to echo the following in PHP:
echo "<td><p style='visibility: hidden' id='joindata$rowindex'>$joindata</p><a style='visibility: visible;' onclick='toggleDisplay('joindata$rowindex'); toggleDisplay('showjoindata$rowindex')' id='showjoindata$rowindex'>Show</a></td>";
But it is not echoing due to the nested ' ' Any Ideas how I can echo HTML elements which have events which call javascript functions which have parameters in PHP would be much appreciated, thanks :)
Just use double-quotes to delimit your attribute values, and escape them in your PHP string:
echo "<td><p style=\"visibility: hidden\" id=\"joindata$rowindex\">$joindata</p><a style=\"visibility: visible;\" onclick=\"toggleDisplay('joindata$rowindex'); toggleDisplay('showjoindata$rowindex')\" id=\"showjoindata$rowindex\">Show</a></td>";
Or, you could separate behaviour from content and just add the event handlers dynamically.
You have to add some double quotes, Try this:
echo "<td><p style=\"visibility: hidden\" id=\"joindata".$rowindex."\">$joindata</p><a style=\"visibility: visible;\" onclick=\"toggleDisplay('joindata".$rowindex."'); toggleDisplay('showjoindata".$rowindex."')\" id=\"showjoindata".$rowindex."\">Show</a></td>";
PHP have best performance and scalability when you separate the views from the data. However in this case you could do:
<td>
<p style="visibility: hidden" id="joindata<?php echo $rowindex; ?>">
<?php echo $joindata; ?>
</p>
<a style="visibility:visible" onclick="toggleDisplay('joindata<?php echo $rowindex; ?>'); toggleDisplay('showjoindata<?php echo $rowindex; ?>')" id="showjoindata<?php echo $rowindex; ?>">Show</a>
</td>
Also take a look on the jQuery docs to avoid hard-coding the javascript functions. Your app will run faster.

echo line returns in html source code

How do you implement line returns when the html code is between simple quotes. The only way I found is to concatenate the line return between double quotes:
echo '<div>'."\n"
.'<h3>stuff</h3>'."\n"
.'</div>'."\n";
Which lucks ugly to me.
Edit: The code between the simple quotes is quite long and with many attributes otherwise I would just use double quotes.
echo "<div>\n" .
"<h3>stuff</h3>\n" .
"</div>\n";
or
echo "<div>
<h3>stuff</h3>
</div>\n";
or
echo <<< HTML
<div>
<h3>stuff</h3>
</div>
HTML;
But this is completely subjective.
You can do
echo "<div>\n<h3>stuff</h3>\n</div>\n";
or
echo '<div>
<h3>stuff</h3>
</div>
';
Concatenation: echo '<div>' . "n";
Concatenation with constant: echo '<div>' . PHP_EOL;
Hard line feeds:
echo '<div>
';
End PHP mode: echo '<div>'; ?>
Double quotes: echo "<div>\n";
Heredoc:
echo <<<EOM
<div>
EOM;
Single quotes inhibit backslash sequences. But newlines are pretty much optional outside of CDATA sections, so feel free to omit them.
echo <<<EOM
<div>
<h3 class="blabla" style='booboo' >stuff<h3>
</div>
EOM;
Using the <<< quotation, you don't need to escape any characters(they are simply outputted exactly how they are typed.

What's the final solution to set html attributes with PHP?

I'm now doing it this way:
<a title="<?php echo $title; ?>">...
But it will brreak when " is included in $title.
Not that it's "the final solution", but obviously you need to escape any literal string that isn't mean to contain HTML. In this case:
<a title="<?php echo htmlspecialchars($title); ?>">
You should run that through htmlspecialchars first to make sure your HTML won't break.
You should translate special characters into HTML entities first, easily done with htmlentities().
<a title="<?php echo htmlentities($title); ?>">

Categories