2016-02-27 68 views
6

我想写一个新行与PHP文件,我收到以下错误:为什么我在PHP中出现语法错误?

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) 

这是我的代码:

public function add_line($line, $value, $file){ 

     $CI =& get_instance(); 
     $CI->load->helper('file'); 

     foreach($this->existing_langs as $lang){ 

      $lang_contents = read_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php'); 

      $new_contents = $lang_contents."\n$lang['".$line."'] = '".$value."';"; //Error happens on this line 

      write_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php', $new_contents, 'w+'); 

     } 

    } 

我已经指出了行了用php评论发生错误。这条线有什么问题? lang_contents的

实施例:new_contents的

<?php 
$lang['1234'] = 'Restaurants'; 

实施例:

<?php 
$lang['1234'] = 'Restaurants'; 
$lang['1235'] = 'Transportation'; 

回答

7

如果你想要写$lang作为字符串文件

$lang_contents."\n".'$lang'."['".$line."'] = '".$value."';"; 

封闭$lang"将只访问您的$lang这是否是数组。因为您在文件路径中使用$lang。我认为这不是一个数组。因此,使用..."\n$lang['".$line."']...只会调用$lang用双引号中$line

3

尝试这种

public function add_line($line, $value, $file){ 

     $CI =& get_instance(); 
     $CI->load->helper('file'); 

     foreach($this->existing_langs as $lang){ 

      $lang_contents = read_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php'); 

      $new_contents = $lang_contents."\n$lang\['".$line."'] = '".$value."';"; //Error happens on this line 

      write_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php', $new_contents, 'w+'); 

     } 

    } 
+0

你几乎已经......但是$ lang应该是文字。 – ShoeLace1291

3

这将具有可变$lang的值。

$new_contents = $lang_contents."\n" . $lang . "['".$line."'] = '".$value."';"; 
4

这可能是字符串试图获取$ lang作为一个值。双引号允许变量在那里传递值。使用单引号。试试看看会发生什么。

试试这行代码

$new_contents = $lang_contents . "\n".'$lang[\'' . $line . '\'] = \'' . $value . '\';'; 

编辑:为了写这个最干净的方式做到这一点

$new_contents = "$lang_contents\n\$lang['$line'] = '$value';"; 
+0

关闭,但\ n从字面上返回。 – ShoeLace1291

+0

再试一次,编辑后。 –

4

字符串进行评估的指标:在你的代码,PHP会评估$lang[但因为PHP预计$lang(变量)或$lang[n](数组中此产生一个错误)。

你想要的输出是什么?

如果你希望输出字面上$其次lang人物,你必须逃脱$

$new_contents = $lang_contents."\n\$lang['".$line."'] = '".$value."';"; 

如果你想输出$lang变量后跟一个[的内容,你必须写:

$new_contents = $lang_contents."\n$lang"."['".$line."'] = '".$value."';"; 

否则,如果要输出$lang[$line]数组项的内容,则必须写入:

$new_contents = $lang_contents."\n{$lang[$line]} = '".$value."';"; 
相关问题