2012-01-12 49 views
1

在此先感謝。php代碼從.php文件中抓取一組字符給出錯誤信息

警告:使用下面的代碼時

獲取此警告的file_get_contents(test.php的)function.file-GET-內容]:未能打開流:在/路徑/索引沒有這樣的文件或目錄。 PHP在線so-n-so。

下面是我使用的代碼,

<?php 

// Scan directory for files 
$dir = "path/"; 
$files = scandir($dir); 

// Iterate through the list of files 
foreach($files as $file) 
{ 
// Determine info about the file 
$parts = pathinfo($file); 

// If the file extension == php 
if ($parts['extension'] === "php") 
{ 
// Read the contents of the file 
$contents = file_get_contents($file); 

// Find first occurrence of opening template tag 
$from = strpos($contents, "{{{{{"); 

// Find first occurrence of ending template tag 
$to = strpos($contents,"}}}}}"); 

// Pull out the unique name from between the template tags 
$uniqueName = substr($contents, $from+5, $to); 

// Print out the unique name 
echo $uniqueName ."<br/>"; 
} 
} 
?> 

回答

4

該錯誤消息說,該文件未找到。

這是因爲scandir()僅返回目錄中文件的基本名稱。它不包括目錄名稱。你可以使用glob()代替:

$files = glob("$dir/*.php"); 

這在結果列表中返回的路徑,也會使您的分機支票冗餘。

+0

是的,它是找到的文件。但是'file_get_contents'在不知道路徑的情況下無法讀取它。而你的代碼目前只傳遞''file.php''而不是''path/file.php''到file_get_contents;因此錯誤消息。 – mario 2012-01-12 23:14:13

+0

感謝它的工作! – KGDD 2012-01-12 23:27:10

1

我建議您需要從scandir()DOCs接收的文件列表中排除...

// Iterate through the list of files 
foreach($files as $file) { 
    if('.' == $file or '..' == $file) { 
     continue; 
    } 
... 

而且你需要在文件名前把路徑:

$contents = file_get_contents($path . $file);