Home >Backend Development >PHP Tutorial >PHP curl usage examples, phpcurl examples_PHP tutorial
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.