php在同一文件上自动生成代码


php auto generate code on the same file

以下代码生成一个新的php文件playlist.php,其中包含$start$result变量中的代码

$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>'n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
$inF = fopen($Fnm,"w");
fwrite($inF,$start."'n");
while( $file = readdir($folder) ) {
 if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
 $result="<entry>'n<title>$file</title>'n<ref href='$path2$file'/>'n<param name='image'     value='preview.jpg'/>'n</entry>'n";
     fwrite($inF,$result);
 }
}
fwrite($inF,"</asx>");
closedir($folder);
fclose($inF);

我想在指定行号上包含此代码的同一文件中生成相同的代码这可能吗?

上面的php脚本在一个新文件上生成以下代码http://tinypaste.com/ff242cd6

以下是如何附加:

$path = "./files/";
$path2="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["PHP_SELF"])."/files/";
//echo $path2;
$folder = opendir($path);
$start="<asx version='3.0'>'n<title>Example ASX playlist</title>";
$Fnm = "./playlist.php";
// build content
$fileContent=$start.'/n';
while( $file = readdir($folder) ) {
 if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
 $result="<entry>'n<title>$file</title>'n<ref href='$path2$file'/>'n<param name='image'     value='preview.jpg'/>'n</entry>'n";
     //append to content
$fileContent .= $result;
 }
}
     //append to content
$fileContent .= "</asx>";
// append to file and check status
if ( file_put_contents(__FILE__ , $fileContent , FILE_APPEND) === false )
{
echo "failed to put contents in ".__FILE__."<br>";
}

这样就可以了…

编辑:

好吧,在我开始之前,你应该先看看一些基本的PHP教程,这些教程可以在网上找到。

因此,与其将内容写入文件,不如直接回显它,并在回显时添加动态内容:

$title='the title of your playlist';
$start="<asx version='3.0'>'n<title>".$title."</title>/n";
while( $file = readdir($folder) ) {
 if (($file != '.')&&($file != '..')&&($file != 'index.htm')){
 $result="<entry>'n<title>$file</title>'n<ref href='$path2.$file'/>'n<param name='image'     value='preview.jpg'/>'n</entry>'n";
}
}
$endCont = $start.$result."</asx>";
echo $endCont;

我创建了一个名为$title的新变量。的值将是输出中生成的标题。您也可以像使用<entry>'n<title>$file</title>一样使用其他标记来执行此操作。

echo highlight_file(__FILE__,true);  

http://www.php.net/manual/en/function.show-source.php

这将使您返回当前文件的源代码。