Home  >  Article  >  Backend Development  >  Introduction to the Application and Differences of PHP fopen() and file_get_contents()_PHP Tutorial

Introduction to the Application and Differences of PHP fopen() and file_get_contents()_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:35:39804browse

Copy code The code is as follows:

$file=fopen("11.txt","r")or exit("Unable to open file!");//fopen opens the file. If it does not exist, it will show that it cannot be opened.
$filesize =filesize("11.txt");//Calculate file size
echo fread($file,$filesize);//Read file
fclose($file);//Close File

fopen() example of opening a file, whether

fclose() is used or not is not reflected on the page, but if fclose() is not used, the opened file will always be occupied resource.
fopen() Open URL example:
Copy code The code is as follows:

$web="http:// www.baidu.com"; // http:// cannot be loaded without adding it
$fp=fopen($web,'r');
if($fp){
while(! feof($fp)){
echo fgets($fp);
}
}

feof() checks whether the file has reached the end, and returns 1 if it reaches the end. Returns 0;

fgets() reads line by line.

file_get_contents() example;
Copy code The code is as follows:

$web ="http:/ /www.baidu.com "
$fcontent=file_get_contents($web);
echo $fcontent;

Obviously file_get_contents() is simpler.

And during the experiment, I found that if you don’t add www. in $web ="", it will jump directly, and adding www. will load this page.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/743578.htmlTechArticleCopy the code as follows: $file=fopen("11.txt","r")or exit(" Unable to open file!");//fopen opens the file. If it does not exist, it will show that it cannot be opened. $filesize =filesize("11.txt");//Calculation document...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn