Php webpage Content Retrieval Method Summary

Source: Internet
Author: User

The captured content is filtered by using a regular expression to get the content you want. As for how to use a regular expression to filter the content, I will not introduce it here. If you are interested, the following are several common methods to capture webpage content using php.
1. file_get_contents
PHP code
Copy codeThe Code is as follows:
<? Php
$ Url = "http://www.jb51.net ";
$ Contents = file_get_contents ($ url );
// Use the following code if Chinese characters are garbled
// $ Getcontent = iconv ("gb2312", "UTF-8", $ contents );
Echo $ contents;
?>

2. curl
PHP code
Copy codeThe Code is as follows:
<? Php
$ Url = "http://www.jb51.net ";
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
// Add the following two lines to the webpage for User Detection:
// Curl_setopt ($ ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY );
// Curl_setopt ($ ch, CURLOPT_USERPWD, US_NAME. ":". US_PWD );
$ Contents = curl_exec ($ ch );
Curl_close ($ ch );
Echo $ contents;
?>

3. fopen-> fread-> fclose
PHP code
Copy codeThe Code is as follows:
<? Php
$ Handle = fopen ("http://www.jb51.net", "rb ");
$ Contents = "";
Do {
$ Data = fread ($ handle, 1024 );
If (strlen ($ data) = 0 ){
Break;
}
$ Contents. = $ data;
} While (true );
Fclose ($ handle );
Echo $ contents;
?>

Note:
1. Use file_get_contents and fopen to enable allow_url_fopen. Method: Edit php. ini and set allow_url_fopen = On. When allow_url_fopen is disabled, neither fopen nor file_get_contents can open remote files.
2. Use curl to enable curl. Method: Modify php. ini in windows, remove the semicolon before extension = php_curl.dll, and copy ssleay32.dll and libeay32.dll to C: \ WINDOWS \ system32. Install curl extension in Linux.

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.