PHP IF语句中的Echo变量和HTML
我有以下代码,它完全按照我的预期工作:PHP IF语句中的Echo变量和HTML,php,html,input,if-statement,echo,Php,Html,Input,If Statement,Echo,我有以下代码,它完全按照我的预期工作: <?php if ($a - $b < 1) echo $text; elseif ($a - $b >= 1) echo $a - $b; else echo $a; ?> 但是,现在我还想根据IF语句的结果向echo添加一些HTML <?php if ($a - $b < 1) echo $text; elseif ($a - $b >= 1) echo $a - $b; <input type="
<?php if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
echo $a - $b;
else
echo $a; ?>
但是,现在我还想根据IF语句的结果向echo添加一些HTML
<?php if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
echo $a - $b;
<input type="button" value="<?php echo $button_txt; ?>" id="button" class="button" />
else
echo $a;
<input type="button" value="<?php echo $button2_txt; ?>" id="button" class="button" /> ?>
当我执行此操作时,会出现以下错误:解析错误:语法错误,意外“请尝试此操作
<?php if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
{
echo $a - $b;
?>
<input type="button" value="<?php echo $button_txt; ?>" id="button" class="button" />
<?php
else
{
echo $a;
?>
<input type="button" value="<?php echo $button2_txt; ?>" id="button" class="button" />
<?php } ?>
您需要回显您的html行:
<?php if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
echo $a - $b;
echo "<input type=\"button\" value=\"$button_txt\" id=\"button\" class=\"button\" />";
else
echo $a;
echo "<input type=\"button\" value=\"$button2_txt\" id=\"button\" class=\"button\" /> ?>
编辑:更好的格式
<?php if ($a - $b < 1): ?>
<?php echo $text ?>
<?php elseif ($a - $b >= 1): ?>
<?php echo $a - $b ?>
<input type="button" value="<?php echo $button_txt ?>" id="button" class="button" />
<?php else: ?>
<input type="button" value="<?php echo $button2_txt ?>" id="button" class="button" />
<?php endif ?>
在启动html代码之前,您需要关闭php语句,因此您的代码应该如下所示:
<?php if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
echo $a - $b;
?>
<input type="button" value="<?php echo $button_txt; ?>" id="button" class="button" />
<?php else
echo $a;
?>
<input type="button" value="<?php echo $button2_txt; ?>" id="button" class="button" /> ?>
PHP和HTML是不同的语言,它们的解释不同。
在PHP中没有任何意义,实际上是无效的。
PHP代码位于
标记之间,HTML位于这些标记之外或引号之间(使其成为字符串)
解决办法可以是:
<?php
if ($a - $b < 1)
echo $text;
elseif ($a - $b >= 1)
{
echo $a - $b;
echo '<input type="button" value="' . $button_txt . '" id="button" class="button" />';
}
else
{
echo $a;
echo '<input type="button" value="' . $button2_txt . '" id="button" class="button" />';
}
?>
请注意,实际的HTML代码现在介于'
和'
之间,因为在PHP中它被视为常规文本。
此外,我还添加了括号{
和}
:当if
后面跟着多条指令时,需要括号来指定属于if
的指令的开头和结尾。这同样适用于else
HTML
标记是否应该是if/else链的一部分?如果是这样,您还需要{}
,否则会在else
中出现语法错误。