2016-07-11 41 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