2016-10-25 108 views
1

大家好,你好!PHP寫入.ini文件異常

目前,我想要寫PHP從一個.ini文件,我使用泰奧曼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 

看來,當我在。的變量中,似乎會加上引號。我不知道爲什麼。

如果任何人都可以指出我正確的方向,那真的很感激。謝謝!

回答

0

無論它是否是字符串,它都會刪除引號。

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