【问题标题】:PHP Write to .ini file exceptionPHP写入.ini文件异常
【发布时间】:2017-03-07 19:43:51
【问题描述】:

大家好!

我目前正在尝试从 PHP 写入 .ini 文件,并且我正在使用 Teoman Soygul 的答案和此处的代码:https://stackoverflow.com/a/5695202

<?php
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);
    }

}
   ?>

效果很好,不过,当我将数据保存到其中时,它的一部分在我的 .ini 中显得很奇怪:

[Server]
p_ip = "192.168.10.100"
p_port = 80

似乎当我在变量中有 .'s 时,它似乎加了引号。我不确定为什么。

如果有人能指出我正确的方向,那将不胜感激。谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

    你得到引号是因为你告诉 PHP 把它们放在那里:

        else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
                                       ^^^^
    

    IP 地址不是“数字”——它们是字符串:

    php > var_dump(is_numeric('192.168.10.100'));
    bool(false)
    

    多“点”字符串不是数字。只允许使用一个.

    php > var_dump(is_numeric('192.168'));
    bool(true)
    php > var_dump(is_numeric('192.168.10'));
    bool(false)
    

    【讨论】:

      【解决方案2】:

      无论是否为字符串,这都会删除引号。

      function write_ini_file($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));
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-07
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        • 2011-08-07
        相关资源
        最近更新 更多