PHP curl instance
This article mainly introduces the use of PHP curl instances. This article provides an example to demonstrate how to output directly to the browser and not directly to the browser. For more information, see
Overview
The previous two articles in this blog: Introduction to curl and libcurl and the use of curl in PHP briefly introduced the use of curl in PHP, but the use of curl in PHP is not simple, in particular, curl configuration items. This article will explain several PHP instances so that you can better understand curl.
Instance: capture page
Using curl to capture a page is relatively simple, but here you need to note that curl will directly output the captured page to the browser by default. However, we often encounter the problem of obtaining captured content and processing the content before performing operations. Therefore, two different situations are written here.
Output directly to the browser
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 and we will see the Baidu homepage directly.
Not directly output to the browser
If we do not want the content captured by curl to be directly output to the browser, we need to set "CURLOPT_RETURNTRANSFER" of curl to true, so that the content captured by curl will appear as the return value of the curl_exec () function.
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 PHP5.1.3 and earlier versions must be used together with CURLOPT_BINARYTRANSFER,
* In Versions later than 5.1.3, this configuration item has been deprecated.
*/
// Curl_setopt ($ ch, CURLOPT_BINARYTRANSFER, TRUE );
$ Content = curl_exec ($ ch );
Var_dump ($ content );
Curl_close ($ ch );
?>
Run the code. We can see that the source code of the obtained webpage is output on the page.