2017-08-20 86 views
0

我是PHP新手,目前正在處理文件處理。我有一個文本文件,我試圖打開閱讀/追加使用骨架腳本。該文件正在輸出並顯示它正在成功打開,但僅當我在代碼中添加包含功能時纔會顯示。我有我的代碼在下面,有人可以看看它,並告訴我,如果我做得對,因爲它對我來說是正確的,並且它確實輸出了,但我不是100%正面的。PHP:當我添加包含函數時,我的文本文件才被讀取

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt'; 
include($location); 

if (file_exists($location) && $file = fopen($location, 'r')){ 
    $file_content = fread($file, filesize($location)); 
    fclose($file); 
} else { 
    echo 'File not found'; 
} 

回答

2

你的代碼讀取和輸出文件更改爲如下:

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt'; 
//include($location); remove include 

if (file_exists($location) && $file = fopen($location, 'r')){ 
    $file_content = fread($file, filesize($location)); 
    echo $file_content; //<----echo here to display content 
    fclose($file); 
} else { 
    echo 'File not found'; 
} 
1

另一種選擇是使用的file_get_contents()。
它也會讀取文本文件,但它會將文本文件的全部內容讀取到一個字符串中。

$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt'; 

if (file_exists($location)){ 
    $file_content = file_get_contents($file); 
    Echo $file_content; 
    $file_content .= " And some more"; //append string to end of string 
    Echo $file_content; // echo with appended string. 
    File_put_contetnts($file, $file_content); // save the original text plus the appended. 
} else { 
    echo 'File not found'; 
} 
相關問題