1. Use of fopen
CopyCode The Code is as follows: <? PHP
$ Handle = fopen ("http://s.jb51.net/", "rb ");
$ Contents = "";
While (! Feof ($ handle )){
$ Contents. = fread ($ handle, 8192 );
}
Fclose ($ handle );
Echo $ contents; // output the obtained content.
?>
Copy codeThe Code is as follows: // the following code can be used for PHP 5 and later versions:
<? PHP
$ Handle = fopen ("http://s.jb51.net", "rb ");
$ Contents = stream_get_contents ($ handle );
Fclose ($ handle );
Echo $ contents;
?>
However, the above Code is prone to failed to open stream: http request failed! Error. Solution
Some people say that in PHP. in INI, there are two options: allow_url_fopen = on (indicating that remote files can be opened through URL), user_agent = "php" (indicating which script is used to access the network. By default, there is "; "Remove it .) Restart the server.
However, some of them still have this warning message. If you want to use the perfect solution, you still have to set PHP. user_agent in ini. The default user_agent in PHP is Php. We can change it to Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) to simulate the browser.
User_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0 )"
If you encounter this problem at work and solve it perfectly, share it with you.
2. Implemented through curl
Copy codeThe Code is as follows: <? PHP
$ Url = "http://s.jb51.net ";
$ CH = curl_init ();
Curl_setopt ($ ch, curlopt_url, $ URL );
Curl_setopt ($ ch, curlopt_returntransfer, 1 );
Curl_setopt ($ ch, curlopt_connecttimeout, 10 );
$ Dxycontent = curl_exec ($ ch );
Echo $ dxycontent;
?>
In Linux, you can download the following code:
Exec ("wget {$ URL }");
Difference between the function fopen/file_get_contents/curl for PHP to capture external resources
Fopen/file_get_contents performs a new DNS query every time a request is sent, and the DNS information is not cached.
However, curl automatically caches DNS information. Only one DNS query is required for a webpage or image request under the same domain name.
This greatly reduces the number of DNS queries.
Therefore, curl performance is much better than fopen/file_get_contents.
The original content of the script home. For more information, see the source.