想知道在html中嵌入php的正确方法
我编写了代码来动态创建 HTML 菜单中的国家/地区列表,并且该代码在作为 php 文件运行时可以工作,但是当我尝试将其嵌入到 html 页面中时,它不起作用。
我的代码看起来像
...
<form action=...>
<?php
include("connect.php");
$ret = mysql_query("SELECT * FROM countries");
echo "<select id='countries' name='countries'>";
while($array = mysql_fetch_array($ret)){
echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";
}
echo "</select>";
?>
</form>
这样,它输出 while 循环和 php 字符,但没有输出 html。
I wrote code to dynamically create a list of countries for a menu in HTML, and the code works when run as a php file, but when I tried to embed it in an html page, it didn't work.
My code looked something like
...
<form action=...>
<?php
include("connect.php");
$ret = mysql_query("SELECT * FROM countries");
echo "<select id='countries' name='countries'>";
while($array = mysql_fetch_array($ret)){
echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";
}
echo "</select>";
?>
</form>
with this, it output the while loop and php characters, but none of the html.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为该文件指定
php
扩展名。通常,服务器设置为仅通过 PHP 运行带有
php
扩展名的文件。您可以修改它,但通常最好保留它。Give the file the
php
extension.Generally, servers are set up to only run files with the
php
extension through PHP. You can modify this, but it is generally best to leave it.通常,您不能将 php 代码嵌入 html 文件并将其解释为 PHP。您可能应该使用上面的代码将文件命名为 file.php 而不是 file.html。
Generally, you can't embed php code in an html file and have it interpreted as PHP. You should probably just name the file with the above code file.php instead of file.html.
您可以将代码嵌入到 .php 或 .phtml 文件中,具体取决于您的 Web 服务器配置。 .html 文件将使用内容类型 text/html 呈现,因此将被视为此类,而不通过 mod_php 传递。
You can embed the code in a .php or .phtml file, depending on your web-server configuration. .html files will be rendered with content-type text/html and therefore will be treated as such, without passing it through mod_php.
通常,Web 服务器将配置为将具有 .php 扩展名的文件视为 PHP 文件,而将具有 .html 扩展名的文件视为纯 HTML。
如果您想更改该行为并使具有 .html 扩展名的文件被视为 PHP,您可以使用 Apache 的
ForceType
指令(假设您正在运行 Apache)。就我个人而言,我不建议这样做,但肯定可以这样做。Typically, a web server will be configured to treat files with a .php extension as PHP files but to treat files with a .html extension as plain HTML.
If you want to change that behavior and make it so files that have a .html extension are treated as PHP, you can use Apache's
ForceType
directive (assuming you're running Apache). Personally, I don't recommend doing that, but it certainly can be done.