我有一个.env文件,其中包括以下数据:
DB_PORT=49500
APP_NAME=Python
APP_HTTP_PORT=49502
APP_HTTPS_PORT=49503
我想在我的index.html页面中使用这些变量,比如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>**$APP_NAME** - Summary Page</title>
<link rel="stylesheet" href="style.css" />
</head>
如何在我的index.html页面中使用其他文件(.env文件(中的变量?
您需要使用PHP
读取.env
文件并将这些值返回给JavaScript
(如果需要(。
$filename = "your_env_file.env";
$file = fopen($filename, "r") or die("500 Server Error: Can't open file.");
$content = fread($file, filesize($filename));
fclose($file);
$lines = explode("n", $content);
$info = array();
foreach($lines as $line)
{
$data = explode("=", $line);
$info[$data[0]] = rtrim($data[1], "r");
}
$json_encoded_info = json_encode($info); // to send to JavaScript
/*
* Now we can echo the $info array to the HTML with
* echo $info;
*
* or we can send JS the variables using
*/
echo "<script>
var info = JSON.parse("".$json_encoded_info."");
//Do something with the info here
</script>";
/*
* Unfortunately, this shows all of your .env information in the string.
* A better way is with AJAX.
* See link reference below for more ways to do this.
*/
如何将变量和数据从PHP传递到JavaScript?
这个代码的作用是:
- 读取
.env
文件的所有内容 - 拆分所有行
- 将所有线路信息放入
$info
注释解释了如何处理这些信息(回显到HTML,发送到Javascript(。
看看你的问题,你似乎想用**APP_NAME**
的相应值来替换它。您可以使用Javascript
通过链接的Stack Overflow答案中的一个方法从PHP
(在这种情况下应该是Python(中获取值,然后用从PHP
接收的值替换**APP_NAME**
(或您想要的任何其他键(。