我可以在PHP中读写ini文件中的键/值,就像我们在Java中使用.properties文件一样


Can I read and write key/values from ini files in PHP just like we do with .properties files in Java?

    Properties prop = new Properties();
    prop.load(new FileInputStream("my.properties"));
    prop.setProperty("name", "my name");
    prop.getProperty("name");

在Java中设置和获取属性看起来很简单。我在PHP中搜索了同样的东西,但没有找到任何与此相关的有用的东西。

我在什么地方读到

PHP可以使用parse_ini_file()原生加载和解析。ini文件。

因为我刚开始学习PHP,我找不到任何代码可以像我们在Java中使用。properties文件一样简单地从。ini文件中读取/写入键/值对。我该怎么做呢?

试试这个…

PHP中的

ini文件包含您的配置.....

示例文件ini将看起来像。

    [first_section]
    db = testdb
    host = myhost

    [second_section]
    path = "/usr/local/bin"
    URL = "http://www.example.com/~username"

现在您可以通过

获取该文件的内容
      <?php
      $config_array  = parse_ini_file('sample.ini');
      echo "<pre>";
      print_r($config_array);
      echo "</pre>";
      ?>

输出类似于

Array
 (
[db] => testdb
[host] => myhost
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)

你也可以通过在parse_ini_file

中传递第二个参数'TRUE'来获得section名
$config_array  = parse_ini_file('sample.ini',true);

则输出为

  Array
 (
   [first_section] => Array
    (
        [db] => testdb
        [host] => myhost
    )
   [second_section] => Array
      (
        [path] => /usr/local/bin
        [URL] => http://www.example.com/~username
    )
)

您也可以将配置保存在数组中,以便后续使用,如kingkero所建议的…

在这里阅读更多内容http://www.php.net/manual/en/function.parse-ini-file.php#78221

在PHP中,我认为使用带有配置的数组返回文件更常见(参见php.net/include)

config。

<?php
return array(
    'key1' => 'val1',
    //etc.
);
其他文件:

<?php
$config = include 'config.php';