In PHP, we can escape to HTML in a switch statement like this:
<?php
switch($example) {
case 'caseone': { ?> <p>Case one</p> <?php } break;
case 'casetwo': { ?> <p>Case two</p> <?php } break;
}
?>
Also, we can set variables:
<?php
switch($example) {
case 'caseone': $text = 'Case one'; break;
case 'casetwo': $text = 'Case two'; break;
}
?>
But how can we escape the variable string like in this pseudo code?
<?php
switch($example) {
case 'caseone': $text = { ?> Case one <?php } break;
case 'casetwo': $text = { ?> Case two <?php } break;
}
?>
I’d like to output a lot of HTML this way, but I don’t want to echo it in the switch
because I have to build a string later containing the $text variable and more.
I might be a bit stupid here.
Thank you very much!
This is actually really simple. You’re thing about it wrong. Your second example was what you actually need. You don’t need to “escape” to HTML in order to build up strings (especially if you want to
echothem later). If you do want to remove any chance of XSS attacks, you can usehtmlspecialcharsto escape the HTML.