The correct way to avoid quotes in an HTML string containing PHP variables

I am writing an HTML string that should take some of my PHP variables. However, it seems like I cannot escape the double quotes correctly.

Attempt 1:

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(\''.$configType.'\')"></span></a></span>';

Result:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(\' project\')"=""></span>

Attempt 2:

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction('.'$configType'.')"></span></a></span>';

Result:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(project)"></span>

Close, but it should be 'project'.


Desired Result:

<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction('project')"></span>
+4
source share
4 answers

Here it is, you were one step closer on the first try, you just need to move the double quotes from single quotes.

$html .= '<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("'.$configType.'")"></span></a></span>';

Here you can see a live sample.

+2
source

HEREDOC

$HTML = <<<_E_
<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("$configType")"></span></a></span>
_E_;

Expert mode with NOWDOC and sprintf :

$frame = <<<'_E_'
<span class="badge"><a href="#" style="color:orange"><span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction("%s")"></span></a></span>
_E_;
$HTML = sprintf($frame, $configType);
+1

HTML,

<?php
$configType = 'project';
// etc ...
?>
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true" onclick="sendToProduction(<?= $configType ?>)"></span>

PHP, HTML, . HTML php , , HTML

, ( HTML)

0

, PHP . :

$html .= "<span class='badge'><a href='#' style='color:orange'><span class='glyphicon glyphicon-arrow-up' aria-hidden='true' onclick='sendToProduction('$configType')'></span></a></span>";
0

All Articles