创建ini文件,在PHP中写入值 [英] create ini file, write values in PHP

查看:104
本文介绍了创建ini文件,在PHP中写入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到一个方法,可以让我创建一个新的文件,把它作为一个ini文件(不是php.ini或simiilar ...一个单独的ini文件为每个用户),并使用PHP创建/删除值。 PHP似乎没有提供简单的方法来创建一个ini文件和读/写/删除值。

I cannot find a way that easily lets me create a new file, treat it as an ini file (not php.ini or simiilar... a separate ini file for per user), and create/delete values using PHP. PHP seems to offer no easy way to create an ini file and read/write/delete values. So far, it's all just "read" - nothing about creating entries or manipulating keys/values.

推荐答案

找到下面的代码片段PHP文档的注释:

Found following code snippet from the comments of the PHP documentation:

function write_ini_file($assoc_arr, $path, $has_sections=FALSE) { 
    $content = ""; 
    if ($has_sections) { 
        foreach ($assoc_arr 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 ($assoc_arr as $key=>$elem) { 
            if(is_array($elem)) 
            { 
                for($i=0;$i<count($elem);$i++) 
                { 
                    $content .= $key."[] = \"".$elem[$i]."\"\n"; 
                } 
            } 
            else if($elem=="") $content .= $key." = \n"; 
            else $content .= $key." = \"".$elem."\"\n"; 
        } 
    } 

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

    $success = fwrite($handle, $content);
    fclose($handle); 

    return $success; 
}

用法:

$sampleData = array(
                'first' => array(
                    'first-1' => 1,
                    'first-2' => 2,
                    'first-3' => 3,
                    'first-4' => 4,
                    'first-5' => 5,
                ),
                'second' => array(
                    'second-1' => 1,
                    'second-2' => 2,
                    'second-3' => 3,
                    'second-4' => 4,
                    'second-5' => 5,
                ));
write_ini_file($sampleData, './data.ini', true);

祝你好运!

这篇关于创建ini文件,在PHP中写入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆