2015-03-31 93 views
-1

我的文件看起來像這樣。我需要通過file_put_contents追加一些新的數組鍵。如何在特定位置將文本插入文件?

<?php 
    $translation = array(
     'Wyposażenie' => 'Equipment', 
    ); 
?> 

我不知道該怎麼做。我唯一知道的是我必須使用file_put_contents($file, "'test' => 'new value',", FILE_APPEND | LOCK_EX);,但它會在文件末尾添加新信息。如何在最後一個數組鍵之後追加我的新信息。要得到的東西是:

<?php 
    $translation = array(
     'Wyposażenie' => 'Equipment', 
     'test' => 'new value', 
    ); 
?> 
+1

這不是一個數組。這是*文字*。將內容添加到數組很容易。把它放在隨機文本中不是。 – 2015-03-31 20:45:11

+0

另外,也許使用'json_encode'。但除此之外,修改數組和'var_export'。 – AbraCadaver 2015-03-31 20:48:28

+0

_ @約翰孔德_你想告訴我,這是不可能的? :)那麼把它放到一個字符串中,刪除:'); ?>',然後將數據附加到字符串,然後再次添加'); ?>'最後保存? – 2015-03-31 20:53:43

回答

0

我寫這是我的自我。這裏是我的代碼:

public static function l($string) 
{  
    $string = trim(preg_replace('/\s+/', ' ', $string)); 

    if($_SESSION['lang']=='default') 
    {  
     return $string; 
    } 
    else 
    { 
     $file = 'translations/'.$_SESSION['lang'].'.php'; 

     if (file_exists($file)) 
     { 
      require($file); 

      $search = array_key_exists($string, $translation); 

      if($search && $translation[$string] != ' ') 
      { 
       # ZNALAZŁ TŁUMACZENIE 
       return $translation[$string]; 
      } 
      else 
      { 
       if(!$search) 
       { 
        # NIE ZNALAZŁ TŁUMACZENIA 
        $translation[$string] = ' '; 

        $serialized = "<?php\n\$translation = array(\n\n\n"; 
        while ($array = current($translation)) { 

         if(key($translation)) 
         { 
          $serialized .= "'".key($translation)."'\n=>\n'".current($translation)."',\n\n\n"; 
         } 

         next($translation); 
        } 
        $serialized .= ");\n?>"; 

        file_put_contents($file, $serialized); 
       } 
       if($translation[$string] == ' ') 
       { 
        # ZNALAZŁ PUSTE TŁUMACZENIE 
       } 

       return $string; 
      } 
     } 
     else 
     { 
      return $string; 
     } 
    } 
} 
2

正如在評論中提到別人,這可以更好的方式,但只是針對這種情況在這裏使用JSON是你如何能做到這一點做到:

<?php 
$read = file_get_contents("i.txt"); 

$delete = strrpos($read,");",-1); 

$read = substr($read,0,$delete); 

$new_value = "'test' => 'new value',"; 

$read .= "\r\n\$new_value \r\n);\r\n ?>"; 

file_put_contents('i.txt',$read); 

?> 
1

我很無聊。這不會覆蓋存在的鍵。要覆蓋,扭轉陣列中array_merge()

function add_to_trans($file, $array) { 
    include($file); 
    $result = array_merge($translation, $array); 
    file_put_contents($file, '$translation = ' . var_export($result, true)); 
} 

$new_trans = array('test' => 'new value'); 
add_to_trans('path/to/file.php', $new_trans); 

但你應該重新考慮這一點,將文件保存在一個json_encode()陣列並重新讀取出來。

相關問題