如何使用 PHP 读取和写入 ini 文件

发布于 2024-11-02 08:31:02 字数 531 浏览 3 评论 0原文

我一直在浏览官方 php 文档,但找不到我要找的内容。

http://php.net/manual/en/function.parse-ini-file.php< /a>

我只想要一个函数来编辑和读取 php ini 文件中的值,例如,

[default_colors]
sitebg = #F8F8F8
footerbg = #F8F8F8
link = #F8F8F8
url = #F8F8F8
bg = #F8F8F8
text = #F8F8F8
border = #F8F8F8

lu_link = #F8F8F8
lu_url = #F8F8F8
lu_bg = #F8F8F8
lu_text = #f505f5
lu_border = #F8F8F8
  1. 如何读取属于“lu_link”或“footerbg”的值?
  2. 如何为这些地方写入新值?

I've been looking around the official php documentation but I'm unable to find what I'm looking for.

http://php.net/manual/en/function.parse-ini-file.php

I just want a function to edit and read the value from the php ini file, for instance,

[default_colors]
sitebg = #F8F8F8
footerbg = #F8F8F8
link = #F8F8F8
url = #F8F8F8
bg = #F8F8F8
text = #F8F8F8
border = #F8F8F8

lu_link = #F8F8F8
lu_url = #F8F8F8
lu_bg = #F8F8F8
lu_text = #f505f5
lu_border = #F8F8F8
  1. How do I read the value belonging to "lu_link" or "footerbg"?
  2. How to I write a new value for these places?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暖阳 2024-11-09 08:31:03

这个怎么样:

 $key='option';
 $val='1.2.3.4.5';
 system("sed  -ie  's/\({$key}=\)\(.*\)/\1{$val}/' file.in");

How about this:

 $key='option';
 $val='1.2.3.4.5';
 system("sed  -ie  's/\({$key}=\)\(.*\)/\1{$val}/' file.in");
夜访吸血鬼 2024-11-09 08:31:03

下面是 PHP 目前缺少的 write_ini_file() 的实现,它将创建几乎相同的输入(注释除外):

  • 支持跨平台 (PHP_EOL) 换行添加到部分之间。
  • 处理索引和键值数组。
  • 处理 CONSTANT 样式值。
  • 并且文件锁定保持一致。

来源

<?php
if (!function_exists('write_ini_file')) {
    /**
     * Write an ini configuration file
     * 
     * @param string $file
     * @param array  $array
     * @return bool
     */
    function write_ini_file($file, $array = []) {
        // check first argument is string
        if (!is_string($file)) {
            throw new \InvalidArgumentException('Function argument 1 must be a string.');
        }

        // check second argument is array
        if (!is_array($array)) {
            throw new \InvalidArgumentException('Function argument 2 must be an array.');
        }

        // process array
        $data = array();
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $data[] = "[$key]";
                foreach ($val as $skey => $sval) {
                    if (is_array($sval)) {
                        foreach ($sval as $_skey => $_sval) {
                            if (is_numeric($_skey)) {
                                $data[] = $skey.'[] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
                            } else {
                                $data[] = $skey.'['.$_skey.'] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
                            }
                        }
                    } else {
                        $data[] = $skey.' = '.(is_numeric($sval) ? $sval : (ctype_upper($sval) ? $sval : '"'.$sval.'"'));
                    }
                }
            } else {
                $data[] = $key.' = '.(is_numeric($val) ? $val : (ctype_upper($val) ? $val : '"'.$val.'"'));
            }
            // empty line
            $data[] = null;
        }

        // open file pointer, init flock options
        $fp = fopen($file, 'w');
        $retries = 0;
        $max_retries = 100;

        if (!$fp) {
            return false;
        }

        // loop until get lock, or reach max retries
        do {
            if ($retries > 0) {
                usleep(rand(1, 5000));
            }
            $retries += 1;
        } while (!flock($fp, LOCK_EX) && $retries <= $max_retries);

        // couldn't get the lock
        if ($retries == $max_retries) {
            return false;
        }

        // got lock, write data
        fwrite($fp, implode(PHP_EOL, $data).PHP_EOL);

        // release lock
        flock($fp, LOCK_UN);
        fclose($fp);

        return true;
    }
}

示例输入 .ini 文件(取自 http://php.net/manual/en/function.parse-ini-file.php)

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

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

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

用法示例:

// load ini file values into array
$config = parse_ini_file('config.ini', true);

// add some additional values
$config['main']['foobar'] = 'baz';
$config['main']['const']['a'] = 'UPPERCASE';
$config['main']['const']['b'] = 'UPPER_CASE WITH SPACE';
$config['main']['array'][] = 'Some Value';
$config['main']['array'][] = 'ADD';
$config['third_section']['urls']['docs'] = 'http://php.net';

// write ini file
write_ini_file('config.ini', $config);

<强>生成的.ini文件:

[first_section]
one = 1
five = 5
animal = BIRD

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

[third_section]
phpversion[] = 5.0
phpversion[] = 5.1
phpversion[] = 5.2
phpversion[] = 5.3
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
urls[docs] = "http://php.net"

[main]
foobar = "baz"
const[a] = UPPERCASE
const[b] = "UPPER_CASE WITH SPACE"
array[] = "Some Value"
array[] = ADD

Below is an implementation of write_ini_file() which PHP is currently lacking, it will create an almost identical (except comments) of the input:

  • Supports cross platform (PHP_EOL) new lines added between sections.
  • Handles both index and key value arrays.
  • Handles CONSTANT style values.
  • And file locking to stay consistent.

Source

<?php
if (!function_exists('write_ini_file')) {
    /**
     * Write an ini configuration file
     * 
     * @param string $file
     * @param array  $array
     * @return bool
     */
    function write_ini_file($file, $array = []) {
        // check first argument is string
        if (!is_string($file)) {
            throw new \InvalidArgumentException('Function argument 1 must be a string.');
        }

        // check second argument is array
        if (!is_array($array)) {
            throw new \InvalidArgumentException('Function argument 2 must be an array.');
        }

        // process array
        $data = array();
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $data[] = "[$key]";
                foreach ($val as $skey => $sval) {
                    if (is_array($sval)) {
                        foreach ($sval as $_skey => $_sval) {
                            if (is_numeric($_skey)) {
                                $data[] = $skey.'[] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
                            } else {
                                $data[] = $skey.'['.$_skey.'] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
                            }
                        }
                    } else {
                        $data[] = $skey.' = '.(is_numeric($sval) ? $sval : (ctype_upper($sval) ? $sval : '"'.$sval.'"'));
                    }
                }
            } else {
                $data[] = $key.' = '.(is_numeric($val) ? $val : (ctype_upper($val) ? $val : '"'.$val.'"'));
            }
            // empty line
            $data[] = null;
        }

        // open file pointer, init flock options
        $fp = fopen($file, 'w');
        $retries = 0;
        $max_retries = 100;

        if (!$fp) {
            return false;
        }

        // loop until get lock, or reach max retries
        do {
            if ($retries > 0) {
                usleep(rand(1, 5000));
            }
            $retries += 1;
        } while (!flock($fp, LOCK_EX) && $retries <= $max_retries);

        // couldn't get the lock
        if ($retries == $max_retries) {
            return false;
        }

        // got lock, write data
        fwrite($fp, implode(PHP_EOL, $data).PHP_EOL);

        // release lock
        flock($fp, LOCK_UN);
        fclose($fp);

        return true;
    }
}

Example input .ini file (taken from http://php.net/manual/en/function.parse-ini-file.php)

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

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

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

Example usage:

// load ini file values into array
$config = parse_ini_file('config.ini', true);

// add some additional values
$config['main']['foobar'] = 'baz';
$config['main']['const']['a'] = 'UPPERCASE';
$config['main']['const']['b'] = 'UPPER_CASE WITH SPACE';
$config['main']['array'][] = 'Some Value';
$config['main']['array'][] = 'ADD';
$config['third_section']['urls']['docs'] = 'http://php.net';

// write ini file
write_ini_file('config.ini', $config);

Resulting .ini file:

[first_section]
one = 1
five = 5
animal = BIRD

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

[third_section]
phpversion[] = 5.0
phpversion[] = 5.1
phpversion[] = 5.2
phpversion[] = 5.3
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
urls[docs] = "http://php.net"

[main]
foobar = "baz"
const[a] = UPPERCASE
const[b] = "UPPER_CASE WITH SPACE"
array[] = "Some Value"
array[] = ADD
じее 2024-11-09 08:31:03

这是一个函数版本,它创建一个可以写入文件的字符串。

function IniAsStr(array $a) : string
{
    return array_reduce(array_keys($a), function($str, $sectionName) use ($a) {
        $sub = $a[$sectionName];
        return $str . "[$sectionName]" . PHP_EOL .
            array_reduce(array_keys($sub), function($str, $key) use($sub) {
                return $str . $key . '=' . $sub[$key] . PHP_EOL;
            }) . PHP_EOL;
      });
}

Here's a functional version that creates a string that can be written to a file.

function IniAsStr(array $a) : string
{
    return array_reduce(array_keys($a), function($str, $sectionName) use ($a) {
        $sub = $a[$sectionName];
        return $str . "[$sectionName]" . PHP_EOL .
            array_reduce(array_keys($sub), function($str, $key) use($sub) {
                return $str . $key . '=' . $sub[$key] . PHP_EOL;
            }) . PHP_EOL;
      });
}
做个少女永远怀春 2024-11-09 08:31:03

这是您使用类别选项读取和写入INI文件的函数!

如果您提供多维数组,您的 INI 文件中将包含类别。
或者基本数组将允许您快速读取和写入数据。

有关详细信息,请参阅下面的评论和示例:

### PHP write_ini_file function to use with parse_ini_file: (choose one of the two example arrays below...)
$array = array('category' => array('color' => 'blue', 'size' => 'large'));
// $array = array('color' => 'red', 'size' => 'small');
function write_ini_file($array, $path) {
    unset($content, $arrayMulti);

    # See if the array input is multidimensional.
    foreach($array AS $arrayTest){
        if(is_array($arrayTest)) {
          $arrayMulti = true;
        }
    }

    # Use categories in the INI file for multidimensional array OR use basic INI file:
    if ($arrayMulti) {
        foreach ($array AS $key => $elem) {
            $content .= "[" . $key . "]\n";
            foreach ($elem AS $key2 => $elem2) {
                if (is_array($elem2)) {
                    for ($i = 0; $i < count($elem2); $i++) {
                        $content .= $key2 . "[] = \"" . $elem2[$i] . "\"\n";
                    }
                } else if ($elem2 == "") {
                    $content .= $key2 . " = \n";
                } else {
                    $content .= $key2 . " = \"" . $elem2 . "\"\n";
                }
            }
        }
    } else {
        foreach ($array AS $key2 => $elem2) {
            if (is_array($elem2)) {
                for ($i = 0; $i < count($elem2); $i++) {
                    $content .= $key2 . "[] = \"" . $elem2[$i] . "\"\n";
                }
            } else if ($elem2 == "") {
                $content .= $key2 . " = \n";
            } else {
                $content .= $key2 . " = \"" . $elem2 . "\"\n";
            }
        }
    }

    if (!$handle = fopen($path, 'w')) {
        return false;
    }
    if (!fwrite($handle, $content)) {
        return false;
    }
    fclose($handle);
    return true;
}

write_ini_file($array,'./data.ini');
$readData = parse_ini_file('./data.ini',true);
print_r($readData);

Here is your function to read and write INI files with a category option!

If you provide multi dimensional array, you will have category in your INI file.
Or basic array will allow you to read and write data fast.

See the comments and example below for details:

### PHP write_ini_file function to use with parse_ini_file: (choose one of the two example arrays below...)
$array = array('category' => array('color' => 'blue', 'size' => 'large'));
// $array = array('color' => 'red', 'size' => 'small');
function write_ini_file($array, $path) {
    unset($content, $arrayMulti);

    # See if the array input is multidimensional.
    foreach($array AS $arrayTest){
        if(is_array($arrayTest)) {
          $arrayMulti = true;
        }
    }

    # Use categories in the INI file for multidimensional array OR use basic INI file:
    if ($arrayMulti) {
        foreach ($array AS $key => $elem) {
            $content .= "[" . $key . "]\n";
            foreach ($elem AS $key2 => $elem2) {
                if (is_array($elem2)) {
                    for ($i = 0; $i < count($elem2); $i++) {
                        $content .= $key2 . "[] = \"" . $elem2[$i] . "\"\n";
                    }
                } else if ($elem2 == "") {
                    $content .= $key2 . " = \n";
                } else {
                    $content .= $key2 . " = \"" . $elem2 . "\"\n";
                }
            }
        }
    } else {
        foreach ($array AS $key2 => $elem2) {
            if (is_array($elem2)) {
                for ($i = 0; $i < count($elem2); $i++) {
                    $content .= $key2 . "[] = \"" . $elem2[$i] . "\"\n";
                }
            } else if ($elem2 == "") {
                $content .= $key2 . " = \n";
            } else {
                $content .= $key2 . " = \"" . $elem2 . "\"\n";
            }
        }
    }

    if (!$handle = fopen($path, 'w')) {
        return false;
    }
    if (!fwrite($handle, $content)) {
        return false;
    }
    fclose($handle);
    return true;
}

write_ini_file($array,'./data.ini');
$readData = parse_ini_file('./data.ini',true);
print_r($readData);
你对谁都笑 2024-11-09 08:31:02

您可以简单地将 parse_ini_file 与 PHP4/5 一起使用。

$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

这是文档: http://php.net/manual/en/ function.parse-ini-file.php

要将对象数组写回 ini 文件,请使用下面的非常快速的 & 方法。简单的解决方案:

function write_php_ini($array, $file)
{
    $res = array();
    foreach($array as $key => $val)
    {
        if(is_array($val))
        {
            $res[] = "[$key]";
            foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
        }
        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
    }
    safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{    if ($fp = fopen($fileName, 'w'))
    {
        $startTime = microtime(TRUE);
        do
        {            $canWrite = flock($fp, LOCK_EX);
           // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
           if(!$canWrite) usleep(round(rand(0, 100)*1000));
        } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

        //file was locked so now we can store information
        if ($canWrite)
        {            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

}

You can simply use parse_ini_file with PHP4/5.

$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

Here is the doc: http://php.net/manual/en/function.parse-ini-file.php

To write back an array of objects back to the ini file, use below as a very fast & easy solution:

function write_php_ini($array, $file)
{
    $res = array();
    foreach($array as $key => $val)
    {
        if(is_array($val))
        {
            $res[] = "[$key]";
            foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
        }
        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
    }
    safefilerewrite($file, implode("\r\n", $res));
}

function safefilerewrite($fileName, $dataToSave)
{    if ($fp = fopen($fileName, 'w'))
    {
        $startTime = microtime(TRUE);
        do
        {            $canWrite = flock($fp, LOCK_EX);
           // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
           if(!$canWrite) usleep(round(rand(0, 100)*1000));
        } while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));

        //file was locked so now we can store information
        if ($canWrite)
        {            fwrite($fp, $dataToSave);
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }

}
李不 2024-11-09 08:31:02

PEAR Config_Lite 包可以非常轻松地为您完成几乎所有工作(包括读取和写入)。在这里查看:http://pear.php.net/package/Config_Lite

The PEAR Config_Lite package can do almost all the work (both reading and writing) for you super-easily. Check it out here: http://pear.php.net/package/Config_Lite

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文