Home  >  Article  >  Backend Development  >  PHP curl usage examples, phpcurl examples_PHP tutorial

PHP curl usage examples, phpcurl examples_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:47:23828browse

PHP curl usage examples, phpcurl examples

Overview

The first two articles of this blog: Introduction to curl and libcurl and the use of curl in PHP provide a brief introduction to the use of curl in PHP. However, the use of curl in PHP is not simple, especially the various configuration items of curl. , this article will explain several PHP examples so that everyone can better understand curl.

Example: Grab page

Using curl to capture pages is relatively simple, but one thing to note here is that curl will output the captured page directly to the browser by default. However, what we often encounter is to obtain the crawled content and then perform certain operations on the content. Therefore, two different situations are written here.

Output directly to the browser

Copy code The code is as follows:
$url="www.baidu.com";
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_exec($ch);
curl_close($ch);
?>

Run the above code, we will directly see the Baidu homepage.

Does not output directly to the browser

If we do not want the content captured by curl to be output directly to the browser, then we need to set curl's "CURLOPT_RETURNTRANSFER" to true, so that the content captured by curl will appear as the return value of the curl_exec() function.
Copy code The code is as follows:
$url="www.baidu.com";
$content='';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
/*
*According to the manual, it seems that versions before PHP5.1.3 still need to be used with CURLOPT_BINARYTRANSFER,
*But in versions after 5.1.3, this configuration item has been abandoned.
*/
//curl_setopt($ch, CURLOPT_BINARYTRANSFER,TRUE);
$content=curl_exec($ch);
var_dump($content);
curl_close($ch);
?>

Running the code, we can see that the page outputs the obtained web page source code.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1026059.htmlTechArticlePHP curl usage examples, phpcurl examples overview The first two articles of this blog: Introduction to curl and libcurl and their use in PHP curl gives a brief introduction to the use of curl in PHP, but the use of curl in PHP...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn