读取配置文件方法parse_ini_file($filepath [,$section])
代码:
conn.php
<?php
//连接数据库
//$conn =new mysqli('localhost','root','','test') or die("连接失败<br/>");
//读取配置文件
$ini= parse_ini_file("test.ini");
$conn =new mysqli($ini["servername"],$ini["username"],$ini["password"],$ini["dbname"]) or die("连接失败<br/>");
//操作数据库
$result=$conn->query("select * from cartoon;");
//输出数据
while($row=$result->fetch_assoc()){
print_r($row);
echo "<br/>";
}
//关闭数据库
$conn->close();
?>
test.ini
[mysql]
servername="localhost"
username="root"
password=""
dbname="test"
输出
1、parse_ini_file() 函数解析一个配置文件,并以数组的形式返回其中的设置。
语法:
parse_ini_file(file,process_sections)
2.例子1:
"test.ini" 的内容:
[names] me = Robert you = Peter [urls] first = "http://www.example.com" second = "http://www.w3school.com.cn"
PHP 代码:
<?php $tmp = parse_ini_file("test.ini");
var_dump($tmp); ?>
输出:
array(4) { ["me"]=> string(6) "Robert" ["you"]=> string(5) "Peter" ["first"]=> string(22) "http://www.example.com" ["second"]=> string(26) "http://www.w3school.com.cn" }
例子2:
"test.ini" 的内容:
[names] me = Robert you = Peter [urls] first = "http://www.example.com" second = "http://www.w3school.com.cn"
PHP 代码(process_sections 设置为 true):
<?php $tmp = parse_ini_file("test.ini",true);
var_dump($tmp); ?>
输出:
array(2) { ["names"]=> array(2) { ["me"]=> string(6) "Robert" ["you"]=> string(5) "Peter" } ["urls"]=> array(2) { ["first"]=> string(22) "http://www.example.com" ["second"]=> string(26) "http://www.w3school.com.cn" } }