Use the PHP curl_setopt () function to implement a simple example of crawling Web pages and post data

Source: Internet
Author: User
The previous article to explain the concept of PHP curl_setopt function, it is an extension of PHP library, using the curl_setopt () function can be easily and quickly crawl Web pages (can be used in the acquisition), using it needs to be configured in the php.ini to open.

Extension=php_curl.dll

Now that you can use the PHP curl_setopt function, we'll look at the first usage now:

1. A simple example of crawling a webpage:

The code is as follows:

<?php//Create a new curl resource  $ch = Curl_init ();//Set URL and corresponding options  curl_setopt ($ch, Curlopt_url, "http://www.php.cn/"); curl_setopt ($ch, Curlopt_header, false);//Fetch the URL and pass it to the browser  curl_exec ($ch);//Close the Curl resource and release the system Resource  curl_close ($ CH);?>

The example code above captures a Web page with a domain name of http://www.php.cn/, and the code runs as follows:


2. Post Data case:

When using curl, there are often data interactions, so it's more important.

<?php       $ch = Curl_init ();       /* Note here that the data to be submitted cannot be a two-dimensional array or higher      * For example, array (' Name ' =>serialize (' tank ', ' Zhang '), ' sex ' =>1, ' birth ' = > ' 20101010 ')      * such as array (' Name ' =>array (' tank ', ' Zhang '), ' sex ' =>1, ' birth ' = ' 20101010 ') This will be an      error */ $data = Array (' name ' = ' = ' test ', ' sex ' =>1, ' birth ' = ' 20101010 ');       curl_setopt ($ch, Curlopt_url, ' http://localhost/mytest/curl/upload.php ');       curl_setopt ($ch, Curlopt_post, 1);       curl_setopt ($ch, Curlopt_postfields, $data);       Curl_exec ($ch);       ? >

In the upload.php file, Print_r ($_post); Use curl to scratch out the contents of the upload.php output array ([name] + test [sex] = 1 [birth] + 20101010)

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.