How to write php within html within php?

旧街凉风 提交于 2019-12-12 02:55:01

问题


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


来源:https://stackoverflow.com/questions/20237175/how-to-write-php-within-html-within-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!