为什么 php 标签在 html 文件中不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22776583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:15:35  来源:igfitidea点击:

Why php tag is not working in html file?

phphtmlforms

提问by Bernard

I have a register.php file and I have defined $name="" inside that file

我有一个 register.php 文件,并且在该文件中定义了 $name=""

global $name;
$name = "";

and now in the html form I have:

现在在 html 表单中我有:

    <form name="register" action="register.php" method="post" class="smart-green">


        <h1>Contact Form
            <span>Registration Form</span>
        </h1>
        <label>
            <span>Username:</span>
            <input id="name" type="text" name="username" value ="<?php echo $name;?>" placeholder="Enter your user name" maxlength="20" />
        </label>
   </form>

But the output is <?php echo $name; ?>instead of empty! Any idea of how I can fix this?

但是输出<?php echo $name; ?>不是空的!知道如何解决这个问题吗?

回答by user1720897

Your web server will server the HTML page as is. It will only parse the HTML as best as it can. If you rename your page with a PHP extension, the web server will parse it using the PHP interpreter and that is when PHP will be interpreted. Also as Fred points out in the comments you can tell Apache to treat HTML as PHP.

您的 Web 服务器将按原样为 HTML 页面提供服务。它只会尽可能地解析 HTML。如果您使用 PHP 扩展名重命名页面,Web 服务器将使用 PHP 解释器解析它,这也是 PHP 将被解释的时候。同样,正如 Fred 在评论中指出的那样,您可以告诉 Apache 将 HTML 视为 PHP。

回答by Aris

rename the form file to '.php' in order for php tag to be interpreted.

将表单文件重命名为“.php”,以便解释 php 标签。

In a php file you can have both php and html code, but not the other way around.

在 php 文件中,您可以同时拥有 php 和 html 代码,但反过来不行。

回答by Suku

That right, for the file to be recognized as php it's extension should be ex- form.php that way it can be executed to give the output

没错,对于要被识别为 php 的文件,它的扩展名应该是 ex-form.php 这样就可以执行它以提供输出