Example of php file reading and writing methods

Source: Internet
Author: User
Tags explode php file readable

Php file writing method

Instance 1

The code is as follows: Copy code
$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_writable ($ filename )){
Exit ('is not writable ');
    }
$ Handle = fopen ($ filename, "a + B ");
$ Content = 'This is test word ';
$ Content. = "n ";
Fwrite ($ handle, $ content );
Fclose ($ handle );
} Else {
Exit ('file is not exists ');
}

Instance 2

The code is as follows: Copy code

$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_writable ($ filename )){
Exit ('is not writable ');
    }
$ Content = 'This is test word ';
$ Content. = "n ";
File_put_contents ($ filename, utf8_encode ($ content ));
} Else {
Exit ('file is not exists ');
}


Php reads files

Instance 1

The code is as follows: Copy code

$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_readable ($ filename )){
Exit ('is not readable ');
            }
$ Contents = file_get_contents ($ filename );
$ Contents = explode ("n", $ contents );
Print_r ($ contents );
} Else {
Exit ('file is not exists ');
        }

Instance 2

The code is as follows: Copy code

$ Filename = 'test.txt ';
$ Filename = dirname (_ FILE _). '/'. $ filename;
If (file_exists ($ filename )){
If (! Is_readable ($ filename )){
Exit ('is not readable ');
    }
$ Handle = fopen ($ filename, "rb ");
$ Contents = fread ($ handle, filesize ($ filename ));
// $ Contents = stream_get_contents ($ handle); // You can also use the method to replace the previous row.
$ Contents = explode ("n", $ contents );
Fclose ($ handle );
Print_r ($ contents );
} Else {
Exit ('file is not exists ');
}

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.