2010-07-12 17 views
0

誰能告訴方法修改/刪除使用PHP文件中使用PHP

+0

可能重複的[使用php清除文本文件的內容](http://stackoverflow.com/questions/1073609/clearing-content-of-text-file-using-php) – Gordon 2010-07-12 18:36:16

+1

*(tutorial)* [Practical PHP - 第8章:文件](http://www.tuxradar.com/practicalphp/8/0/0) – Gordon 2010-07-12 18:38:08

回答

2

一個文本文件的內容,通過使用fopen處理:

if (is_writable($filename)) { 
    if (!$handle = fopen($filename, 'w')) { 
    echo "Cannot open file ($filename)"; 
    exit; 
    } 
    if (fwrite($handle, $somecontent) === FALSE) { 
    echo "Cannot write to file ($filename)"; 
    exit; 
    } 

    echo "Success, wrote to file ($filename)"; 

    fclose($handle); 
} 

寫「」到要刪除的文件的內容。

通過線使用要刪除的內容行:

$arr = file($fileName); 

unset($arr[3]); // 3 is an arbitrary line 

然後寫入文件內容。或者你指的是內存映射文件?

+0

您可以使用串流尋求http://uk3.php.net/manual/en/streamwrapper.stream- seek.php並編寫http://uk3.php.net/manual/en/streamwrapper.stream-write.php如果你使用fopen。 – Metalshark 2010-07-12 18:45:07

+0

本教程可能會爲您提供您所需(二進制文件 - 如此低級別的文件編輯)http://en.kioskea.net/faq/998-parsing-a-binary-file-in-php – Metalshark 2010-07-12 18:48:15

+0

非常感謝...陣列功能運行良好。 – ayush 2010-07-12 18:58:37

3

使用file_put_contents

file_put_contents($filename, 'file_content'); 

如果要追加到文件而不是替換它的內容使用方法:(file_out_contents是使用整個fopen複雜的簡單的替代)

file_put_contents($filename, 'append_this', FILE_APPEND); 

1

有很多方法可以讀取文件。大文件可以很快處理使用

$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text 
while (!feof ($fd)) 
{ 
    $buffer = fgets($fd, 4096); 
    $lines[] = $buffer; 
} 
fclose ($fd); 

您還可以使用file_get_contents()來讀取文件。它實現同樣事物的簡短方法。

修改或附加文件,你可以使用

$filePointer = fopen("log.txt", "a"); 
fputs($filePointer, "Text HERE TO WRITE"); 
fclose($filePointer); 

你還可以將文件加載到陣列,然後執行搜索操作刪除的磁盤陣列的特定元素。

$lines = file('FILE WITH COMPLETE PATH.'); //單個SLASH應該在路徑中雙擊如C://PATH//TO//FILE.TXT 上面的代碼將加載$ lines數組中的文件。