Home > Article > Backend Development > A simple example of using the php curl_setopt() function to capture web pages and POST data
The previous article explained to you the concept of the curl_setopt function in PHP. It is an extension library of PHP. Using the curl_setopt() function can easily and quickly crawl web pages (can be used for collection) , using it needs to be configured and enabled in php.ini.
extension=php_curl.dll
Now you can use the php curl_setopt function, so let’s look at the first usage first:
1. A crawled web page A simple case:
The code is as follows:
<?php // 创建一个新cURL资源 $ch = curl_init(); // 设置URL和相应的选项 curl_setopt($ch, CURLOPT_URL, "http://www.php.cn/"); curl_setopt($ch, CURLOPT_HEADER, false); // 抓取URL并把它传递给浏览器 curl_exec($ch); //关闭cURL资源,并且释放系统资源 curl_close($ch); ?>
The above example code captures a domain name of http://www.php. cn/ web page, the code execution result is as follows:
##2. POST data case:
When using curl, there will often be data interaction, so it is more important.
<?php $ch = curl_init(); /*在这里需要注意的是,要提交的数据不能是二维数组或者更高 *例如array('name'=>serialize(array('tank','zhang')),'sex'=>1,'birth'=>'20101010') *例如array('name'=>array('tank','zhang'),'sex'=>1,'birth'=>'20101010')这样会报错的*/ $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); can use curl to grab the content Array output by upload.php ( [name] => test [sex] => ; 1 [birth] => 20101010 )【Recommended related articles】1.
php curl_setopt function concept and usage examples
2 .Detailed explanation of usage examples of PHP curl_exec function
The above is the detailed content of A simple example of using the php curl_setopt() function to capture web pages and POST data. For more information, please follow other related articles on the PHP Chinese website!