How to write php within html within php?

2019-09-09 06:39发布

问题:

I have recently asked this question, but rather than getting a direct answer, I was shown how to use the ternary operator to simplify my code by substituting if statements inside my html with variables, which I appreciated and put to use - however that also caused other code to be harder to read and ultimately did not teach me to properly escape/parse php in code similar to that below.

So I would love a simple 'show and tell' of how to make the following code parse, thank you:

<?php
if (!isset($_POST['myform'])) {
  echo

<form method="POST" action="<?php if (isset($myform_worked)) { echo 'somepath'; } ?>" accept-charset="UTF-8">

This is what I've tried, but the line above doesn't parse:

<?php
if (!isset($_POST['myform'])) {
  echo

'<form method="POST" action="'<?php if (isset($myform_worked)) { echo 'somepath'; } ?>'" accept-charset="UTF-8">'

I have also tried (using double quotes around the php inside :

"<?php if (isset($myform_worked)) { echo 'somepath'; } ?>"

Please show this nub how to do this, thanks. I do not care if the above code is BAD... I just need to learn how to escape/parse php inside html inside php, thanks.

回答1:

You did not close the open php-block beforehand. The working Syntax would be like this:

<?php
//php code
?>
<!--HTML-Code-->
<?php
?>

Or according to your problem:

<?php
if (!isset($_POST['myform'])) {
?>

<form method="POST" action="<?php if (isset($myform_worked)) { echo 'somepath'; } ?>" accept-charset="UTF-8">

<?php } //if-closing bracket ?>


回答2:

You forgot to close PHP tag before entering HTML mode.



回答3:

Can you try this, inside php. In php page, adding php code inside the html tags looks like <?php //your php code here ?>.

         <?php
         if (!isset($_POST['myform'])) {
              echo '<form method="POST" action="'.isset($myform_worked)?'somepath':''.'" accept-charset="UTF-8">';
          }
         ?>

HTML+PHP

   <?php if (!isset($_POST['myform'])) { ?>
      <form method="POST" action="<?php if (isset($myform_worked)) { echo 'somepath'; } ?>" accept-charset="UTF-8">
  <?php } ?>


回答4:

<?php echo "hello world";?>

OR Shorthand

<?="hello world"?>