简体   繁体   中英

How can I put HTML tags in a PHP variable?

I am trying to make a variable which contains some HTML tags, this isn't working like I want it to. I was hoping someone could tell what I am doing wrong here.

My Code:

$foto = "put picture here";
$naam = 'Sieraad1';
$prijs = '20,00';

$artikel = '<img src="'$foto'"><h4>'$naam'</h4><h6>€'$prijs'</h6>';

echo '<table><tr><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td></tr>';
echo '<table><tr><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td><td>'.htmlspecialchars(stripslashes($artikel)).'</td></tr>';
echo '</table>';
$artikel = '<img src="'$foto'"><h4>'$naam'</h4><h8>€'$prijs'</h8>';

You are missing . here between the variables for concatenation.

Using htmlspecialchars on html code will convert < to &lt; , > to &gt; and " to &quot; . So it will obviously break your code. Run the htmlspecialchars on the inner contents instead:

$artikel = '<img src="' . htmlspecialchars($foto) . '"><h4>' . htmlspecialchars($naam) . '</h4><h8>€' . htmlspecialchars($prijs) . '</h8>';
echo '<table><tr><td>'.$artikel.'</td>...';

try

$artikel = "<img src=\"'$foto'\"><h4>'$naam'</h4><h8>€'$prijs'</h8>";

or

$artikel = '<img src="' . $foto . '"><h4>' . $naam . '</h4><h8>€' . $prijs .'</h8>';

then just echo the $artikel - you don't need the htmlspecialchars

var concatenation is missing for variable $artikel. replace user code line with below:

$artikel = '<img src="'.$foto.'"><h4>'.$naam.'</h4><h8>€'.$prijs.'</h8>';

easy to use

<?php
echo <<< END
<table class="head"><tr>
  <td class='head'>$name</td>
  <td>$fname</td>
 </tr></table>
END;
?>

or

<?php
echo "<table class='head'><tr>
  <td class='head2'>$name</td>
  <td class='head3'>$fname</td>
 </tr></table>";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM