2011-02-17 47 views
1

我想隨機顯示一個PHP碼等爲我有包括回波內PHP代碼從隨機文本

<?php 

// load the file that contain thecode 
$adfile = "code.txt"; 
$ads = array(); 

// one line per code 
$fh = fopen($adfile, "r"); 
while(!feof($fh)) { 

    $line = fgets($fh, 10240); 
    $line = trim($line); 
    if($line != "") { 
    $ads[] = $line; 
    } 
} 

// randomly pick an code 
$num = count($ads); 
$idx = rand(0, $num-1); 

echo $ads[$idx]; 
?> 

的code.txt具有類似於

<?php print insert_proplayer(array("width" => "600", "height" => "400"), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?> 

Proplayer是一個顯示視頻的wordpress插件。 code.txt中的代碼運行良好,但是當我使用code.txt中的選擇行時不行。我得到的不是完整的php行:

"width" => "600", "height" => "400"), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?> 

我該如何讓echo顯示php代碼,而不是php代碼的txt版本?

+0

把打印語句放在一個php文件中,而不是txt? – 2011-02-17 23:00:37

+0

這整個方法看起來不對,code.txt是如何生成的? – 2011-02-17 23:00:40

回答

0

使用評估:http://php.net/eval

編輯:

或者更好的是,使用包括。這可能是if-else語句,switch語句,數組或任何可以從選項中選擇的內容。例如code.php:

<?php 
    if ($i == 1) // use better variable name 
     print 'blah blah blah'; 
    else if ($i == 2) 
     print 'blah blah blah'; 
    else if ($i == 3) 
     print 'blah blah blah'; 
    // ... 
    else if ($i == $max) 
     print 'blah blah blah 4'; 
?> 

調用頁面:

<?php 
    $max = 5; // set max to however many statements there are 
    $i = rand(1, $max); 
    include('code.php'); 
?> 
1

嘗試使用htmlentities()逃脫PHP代碼。例如:

$string = '<?php print insert_proplayer(array("width" => "600", "height" => "400"), "http://www.youtube.com/watch?v=xnPCpCVepCg"); ?>'; 
echo htmlentities($string);