PHP implementation code for reading webpage files (fopen, curl, etc)

Source: Internet
Author: User

1. fopen implementation code:
Copy codeThe Code is as follows:
<? Php
$ Handle = fopen ("http://www.example.com/", "rb ");
$ Contents = "";
While (! Feof ($ handle )){
$ Contents. = fread ($ handle, 8192 );
}
Fclose ($ handle );
?>

Copy codeThe Code is as follows:
<? Php
// For PHP 5 and later versions
$ Handle = fopen ("http://www.example.com/", "rb ");
$ Contents = stream_get_contents ($ handle );
Fclose ($ handle );
?>

2. curl implementation code:
Copy codeThe Code is as follows:
<? Php
Function _ url ($ Date ){
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, "$ Date ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1 )");
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ Contents = curl_exec ($ ch );
Curl_close ($ ch );
Return $ contents;
}
$ PageURL = "http://www.baidu.com ";
$ Contents = _ url ($ pageURL );
?>

Encoding conversion functions
Copy codeThe Code is as follows:
$ Html = file_get_contents ("http://s.jb51.net ");
$ Html = iconv ("Big5", "UTF-8 // IGNORE", $ html); // convert the encoding method to UTF8
Print $ html;
$ Htm = file ("http://s.jb51.net ");
$ H = "";
Foreach ($ htm as $ value)
{
$ H. = iconv ("GB2312", "UTF-8 // IGNORE", $ value );
}
Print_r ($ h );

Another way to open a webpage
Copy codeThe Code is as follows:
<? Php
$ Opts = array (
'Http' => array (
'Method' => "GET ",
'Header' => "Accept-language: en \ r \ n ".
"Cookie: foo = bar \ r \ n"
)
);
$ Context = stream_context_create ($ opts );
/* Sends an http request to www.example.com
With additional headers shown abve */
$ Fp = fopen ('HTTP: // www.baidu.com ', 'R', false, $ context );
Fpassthru ($ fp );
Fclose ($ fp );
?>

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.