Views: 569 views
Staff,
Good night!
Today we will see how to read and write data to a text file using the PHP web programming language. For this, we will create two functions to assist us in this task:
SaveFileText:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public function gravarArquivoTexto( $strArquivo, $strTexto, $bolApagarSeJaExiste = false, $bolUTF8 = true ) { if ( !is_dir( dirname( $strArquivo ) ) ) { mkdir( dirname( $strArquivo ), 0755, true ); } $strModo = ($bolApagarSeJaExiste) ? "w" : "a"; $criarArquivo = (!is_file( $strArquivo ) ); $objTxt = fopen( $strArquivo, $strModo ); if ( $criarArquivo && $bolUTF8 ) { //UTF-8 fwrite( $objTxt, pack( "CCC", 0xef, 0xbb, 0xbf ) ); } fwrite( $objTxt, $strTexto ); fclose( $objTxt ); } |
ReadFileText:
1 2 3 4 5 6 7 8 9 10 11 12 |
public function lerArquivoTexto( $strArquivo ) { if ( is_file( $strArquivo ) ) { $objTxt = fopen( $strArquivo, "r" ); $texto = fread( $objTxt, filesize( $strArquivo ) ); fclose( $objTxt ); return $texto; } } |
Now let's use the functions (remember, the functions must be contained in a class). Let's instantiate our class. I will name it clsArchive.
1 2 3 4 5 6 7 8 9 |
//Carregando a classe e instanciando require("classes/clsArquivo.php"); $objArquivo = new clsArquivo(); //Lendo um arquivo e armazenando o conteúdo em uma variável: $conteudo = $objArquivo->lerArquivoTexto("C:\Arquivo.txt"); //Gravando o conteúdo de uma variável em um arquivo texto $objArquivo->gravarArquivoTexto("C:\Outro_Arquivo.txt", $conteudo); |
That simple!
To the next!