2014-01-23 54 views
0

下面是腳本:使用file_put_contents將PHP代碼寫入文件的最佳方法是什麼?

<?php 

$line0PHP = '<?php'; 
$line1PHP = 'defined('_JEXEC') or die('Restricted access');'; 
$line2PHP = 'jimport('joomla.plugin.plugin');'; 
$line3PHP = 'jimport('joomla.html.parameter');'; 
$line4PHP = 'class&#32;plgSystem'.$titleString.'plugin&#32;extends&#32;JPlugin'; 
$line5PHP = '{'; 
$line6PHP = 'function plgSystem'.$titleString.'plugin()'; 
$line7PHP = '{'; 
$line8PHP = '}';  
$line9PHP = '}'; 
$line10PHP = '?>'; 

$phpFileOutput = $line0PHP.'&nbsp;'.$line1PHP.'&nbsp;'.$line2PHP.'&nbsp;'.$line3PHP.'&nbsp;'.$line4PHP.'&nbsp;'.$line5PHP.'&nbsp;'.$line6PHP.'&nbsp;'.$line7PHP.'&nbsp;'.$line8PHP.'&nbsp;'.$line9PHP.'&nbsp;'.$line10PHP; 

$varOutputPhp = print_r($phpFileOutput, true); 

file_put_contents($root,$varOutputPhp); 

?> 

$root$titleString較早定義。

+1

小心,你的代碼中有一些「聰明的引號」。 PHP只支持普通的單引號和雙引號。 – Barmar

+0

在寫入文件之前,請考慮[heredoc](http://php.net/heredoc)字符串和['htmlspecialchars'](http://php.net/htmlspecialchars)。 – mario

+0

HTML實體由瀏覽器處理,而不是PHP。您應該將真實的字符寫入文件。 – Barmar

回答

0

您有引用問題,因爲您在單引號字符串中有單引號。您需要轉義它們,或者使用雙引號。而且你還有一些需要用普通字符替換的HTML實體。

<?php 

$line0PHP = '<?php'; 
$line1PHP = "defined('_JEXEC') or die('Restricted access');"; 
$line2PHP = "jimport('joomla.plugin.plugin');"; 
$line3PHP = "jimport('joomla.html.parameter');"; 
$line4PHP = 'class plgSystem'.$titleString.'plugin extends JPlugin'; 
$line5PHP = '{'; 
$line6PHP = 'function plgSystem'.$titleString.'plugin()'; 
$line7PHP = '{'; 
$line8PHP = '}';  
$line9PHP = '}'; 
$line10PHP = '?>'; 
$phpFileOutput = $line0PHP.' '.$line1PHP.' '.$line2PHP.' '.$line3PHP.' '.$line4PHP.' '.$line5PHP.' '.$line6PHP.' '.$line7PHP.' '.$line8PHP.' '.$line9PHP.' '.$line10PHP; 
+0

感謝@Barmar,解決了它。 – Presto

0

下面是編寫代碼的正確方法: file_put_contents($文件名,$ newfilecode);

+0

這有什麼用?這只是不同的變量名稱。 – Barmar

1
$text = "<?php \n"; 
    $text .= "defined('_JEXEC') or die('Restricted access');\n"; 
    $text .= "jimport('joomla.plugin.plugin');\n"; 
    $text .= "jimport('joomla.html.parameter');\n"; 
    $text .= "class plgSystem".$titleStringplugin." extends JPlugin\n"; 
    $text .= "{\n"; 
    $text .= "function plgSystem".$titleString."plugin()\n"; 
    $text .= "{\n"; 
    $text .= "}\n"; 
    $text .= "}\n"; 
    $text .= "?>\n"; 
相關問題