2016-07-11 47 views
0

我試圖從php創建一個新的php文件。在PHP中編寫PHP文件

我最終的PHP文件必須是這樣的:

<? 
    $text_1 = "Text"; 
    $text_2 = "Banana"; 
?> 

其實我的PHP生成它是:

$file = fopen("../lang/_____fr-CA.php", "w") or die("Unable to open file!"); 

<? 
    $datas .= '$text_1 = "Text"; \n '; 
    $datas .= '$text_2 = "Banana"; \n '; 

    $datas = nl2br("&lt;? \n".$datas."\n ?&gt;"); 

    fwrite($file, $datas); 
    fclose($file); 
?> 

我的問題是生成的PHP是這樣的:

&lt;? <br /> 
$text_1 = "Text"; \n$text_2 = "Banana"; \n<br /> 
?&gt; 
+1

能否請您查看以下鏈接:[http://stackoverflow.com/questions/3066421/writing-a-new-line-to-file-in-php](http://stackoverflow.com/questions/3066421 /編寫一個新的文件在php中) –

回答

0

你需要寫你想要的數據。就你而言,你正在編寫HTML。你應該寫出確切的PHP代碼,因爲它應該出現。你不需要nl2br。您還需要了解newlines must be in double quotes。最後,?>是可選的,我建議您省略純PHP文件。

$datas = "<?php \n" . 
    '$text_1 = "Text"; ' . "\n" . 
    '$text_2 = "Banana";'; 
fwrite($file, $datas); 
+0

你幫了我很多。謝謝。 – roberto

0

您需要用雙引號將\n換行,它不會被評估爲行br用單引號括起來。

爲了兼容性的目的,您不應該使用短打開標籤<?,您應該只使用<?php

0

您可以使用更「優雅」的方式像定界符寫入文件:

<? 
    $datas <<<eof 
<?php 
    $text_1 = "Text"; 
    $text_2 = "Banana"; 
?> 
eof; 

    fwrite($file, $datas); 
    fclose($file); 
?> 
+0

我會盡可能避免使用Heredoc。這是一種糟糕的編碼方式。 – Machavity

+0

你爲什麼這麼說?如果你需要爲一個文件編寫代碼,Heredoc將會變得更加清晰,當然,heredoc也會說明這一點:https://en.m.wikipedia.org/wiki/Here_document所以,不要恨我如果我說肯定heredoc是更正確的路要走。 –

+0

單個最大的缺點是你不能縮進heredoc。即使在一個功能。我並不討厭你(我甚至沒有低估它),我只是不推薦它 – Machavity