简体   繁体   中英

Using html in a php echo statement

I'm trying to write html code in a php echo statement but I keep failing.

echo "<option value='$_GET['b']'>$_GET['b']</option>";

error:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in .../web_info.php on line 11

I mean when should I use " and when '? what are the rules?that's so confusing.

try this:

echo "<option value='{$_GET['b']}'>{$_GET['b']}</option>";

The problem was with the quotes and the brackets. Sometimes you need to wrap your variables in curly braces otherwise the PHP parser doesn't know when to start and stop for a variable. It gets mixed up with the rest of the string.

Wrap the variables in curly braces:

echo "<option value='{$_GET['b']}'>{$_GET['b']}</option>";

Or, use sprintf() :

echo sprintf("<option value='%s'>%s</option>", $_GET['b'], $_GET['b']);
echo("<option value='" . $_GET['b'] . "'>" .$_GET['b'] . "</option>");

Simply you can write this ( DEMO )

echo "<option value='$_GET[b]'>$_GET[b]</option>";

Or this ( DEMO )

echo "<option value='" . $_GET['b'] . "'>" . $_GET['b'] . "</option>";

Read more on manual .

echo "<option value='".$_GET['b']."'>".$_GET['b']."</option>";

问题在于value属性中的单引号,您过去常常对它进行计数,而解析器无法理解结尾在哪里。

除了其他答案外,一种不太为人所知的方法是使用逗号(因此,PHP不必进行任何串联):

echo '<option value="', $_GET['b'], '">', $_GET['b'], '</option>';
printf("<option value=\"%s\">%s</option>", $_GET['b'], $_GET['b']);

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