PHP 正在 HTML 之外打印

PHP is printing outside of HTML

我有一个 html 页面,其中嵌入了 php,如下所示:

<html>
<body>
<div>
<?php
function printTable(){
echo '<table></table>';
}
?>
</div>
</body>
</html>
<?php
printTable();
?>

执行时 html 输出为

<html>
<body>
<div>
</div>
</body>
</html>
<table></table>

我希望 table 打印在 de DIV 元素中。我该怎么做?

您只是在标记之后调用您的函数。它应该在你的 div 块中调用,即

<html>
<body>
<div>
<?php
function printTable(){
echo '<table></table>';
}
printTable();
?>
</div>
</body>
</html>
<html>
<body>
<div>
<?php
function printTable(){
echo '<table></table>';
}
printTable();
?>
</div>
</body>
</html>

当您有一个生成输出的函数时,输出将在该函数调用的地方生成,而不是在定义的地方生成.您将其称为 结束 </html> 标记之后,因此它会在该点回显

试试这个:

<html>
<body>
<div>
<?php
function printTable(){
echo '<table></table>';
}
printTable();
?>
</div>
</body>
</html>

这里,我们在<div>中调用printTable()函数。因此,Table 将打印在 div.

<?php
function printTable(){
  return '<table></table>';
}
?>
<html>
 <body> 
 <div>
  <?php echo printTable(); ?>
 </div>
 </body>
</html>

您可以使用:

<?php
function printTable(){
  return '<table></table>';
}
?>
<html>
 <body> 
 <div>
  <?php echo printTable(); ?>
 </div>
 </body>
</html>

或者这样:

<html>
<body>
<div>
<?php
function printTable(){
echo '<table></table>';
}
printTable();
?>
</div>
</body>
</html>