Home  >  Article  >  Backend Development  >  PHP curl usage examples_PHP tutorial

PHP curl usage examples_PHP tutorial

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

PHP curl usage examples

This article mainly introduces PHP curl usage examples. This article directly gives an example to demonstrate direct output to the browser and non-direct output to the browser. Different ways of writing, friends in need can refer to it

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, but 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: Fetch the page

Using curl to capture pages is relatively simple, but one thing to note here is that curl will output the captured pages 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

The code is as follows:

$url="www.baidu.com";

 $ch=curl_init();

curl_setopt($ch,CURLOPT_URL,$url);

curl_exec($ch);

curl_close($ch);

 ?>

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

Does not output directly to the browser

If we don’t 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.

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/1025895.htmlTechArticlePHP curl usage examples This article mainly introduces PHP curl usage examples. This article directly gives an example and the demonstration is straightforward. Different writing methods for outputting to the browser and not outputting directly to the browser require...
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