HTML 会在 2 个打开和关闭的 PHP 标签之间消失吗?



我正在尝试在 for 循环中使用 php 打印表单,我的目标是打印按钮,就像我有数组元素一样多,但是当我尝试在浏览器中执行此操作时,html 表单不会显示在页面上或源代码中。

<div class="col text-center">
<?php
$max = count($array);
for($i = 0 ; $i < $max ; $i++){
$item = $array[$i];
$item = str_replace(' ', '', $item);
?>
<form method="GET" action="page.php?ders=<?php echo $item;?>" target="_blank" name="f1">
<input type="hidden" name="item" value="<?php echo $item;?>">
<a class="btn btn-lg btn-primary"><?php echo $item;?> &raquo;</a>
</form>
<br>
<?php
}
?>
</div>

当我使用命令php脚本在控制台上运行它时.php它显示了所有具有正确值的表单,当我将输出放在页面上时.html它会显示按钮,但我需要页面.php并且php必须在页面上呈现html表单.php在浏览器上,我错过了什么吗?

您的代码存在许多问题。我将尝试逐行指出它们并带有替代方案

$max = count($array);

除非您已经检查了$array是否存在,否则应检查上述行。如果不这样做,最终可能会出现错误:

$max = (isset($array)) ? count($array) : 0;

这两条线可以从以下位置压缩:

$item = $array[$i];
$item = str_replace(' ', '', $item);

到以下内容。这确实是个人的事情。注意:稍后渲染$item.如果$item可以是任何内容,您将需要使用htmlentities()来确保您的页面不容易受到XSS攻击。

$item = str_replace(' ', '', $array[$i]);

现在这条线很有趣。您正在为每个$item创建一个新表单。这真的是你想做的吗?

<form method="GET" action="page.php?ders=<?php echo $item;?>" target="_blank" name="f1">

无论哪种方式,您真的想包含属性target="_blank"吗?

下一个问题是您已为每个表单指定了相同的名称,并带有name="f1".如果不是现在,这很可能会引起问题,那么任何扩展都会导致问题。像下面这样的东西会更好:

<form method="GET" action="page.php?ders=<?=$item?>" name="f1<?=$item?>">

我相信的下一句话是在暗示你真正想要什么。基本上,它使其余代码看起来毫无意义,除非您确实需要提交表单page.php,我认为您不会这样做,因为您已经将查询字符串变量ders设置为表单action属性。

<a class="btn btn-lg btn-primary"><?php echo $item;?> &raquo;</a>

我认为您可能拥有以下内容并删除了几乎所有其他内容:

<a href="page.php?ders=<?=$item?>" class="btn btn-lg btn-primary"><?=$item?> &raquo;</a>

根据我认为您正在尝试做的事情,您应该能够将其重写为:

<div class="col text-center">
<?php
$max = (isset($array)) ? count($array) : 0;
if (! $max) {
echo 'No items in array to render!';
} else {
for($i=0;$i<$max;$i++){
$item = str_replace(' ', '', $array[$i]);
// make the following one line
echo '<a href="page.php?ders='.$item.'" 
class="btn btn-lg btn-primary"
target="_blank">'.$item.' &raquo;</a>
<br />';
}
}
?>
</div>
<div class="col text-center">
<?php
foreach($array as $value):
$item = str_replace(' ', '', $value); ?>
<form method="GET" action="page.php?ders=<?= $item;?>" target="_blank" name="f1">
<input type="hidden" name="item" value="<?= $item;?>">
<a class="btn btn-lg btn-primary"><?= $item;?> &raquo;</a>
</form>
<br>
<?php endforeach; ?>
</div>

最新更新