简体   繁体   中英

PHP is printing outside of HTML

I have a html page with php embedded inside which looks like this:

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

when executed the html output is

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

I want the table to be printed inside de DIV element. How can i do that?

When you have a function that generates output, the output will be generated where that function is called , not where it is defined . You're calling it after the closing </html> tag, so it will be echoed at that point

You are only calling your function after the tag. It should be called within your div block,ie

<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>

Try this :

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

Here, we call printTable() function inside the <div> . So, Table will be printed in the div.

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

You can use :

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

Or this:

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

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