Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What for do we use CURLOPT_WRITEFUNCTION in PHP's cURL?

Tags:

php

curl

Could you describe it in examples, please?

like image 634
MrY Avatar asked Feb 19 '10 05:02

MrY


People also ask

What is Curl_setopt used for?

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

What is the use of Curlopt_returntransfer?

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

What is Curlopt_encoding?

CURLOPT_ENCODING only tells the server what types of encoding it will accept. So either way the data will only be decoded if needed. But by giving CURLOPT_ENCODING a value you are limiting your call to only accept one type of encoding.

What is Curl_init?

The curl_init() function will initialize a new session and return a cURL handle. curl_exec($ch) function should be called after initialize a cURL session and all the options for the session are set. Its purpose is simply to execute the predefined CURL session (given by ch).


1 Answers

I know this is an old question, but maybe my answer will be of some help for you or someone else. The WRITEFUNCTION is useful for processing text as it comes streaming in or for aborting the download based on some condition. Here's an example that simply puts all the text into uppercase letters:

function get_html($url){
    $ch = curl_init();
    $obj = $this;//create an object variable to access class functions and variables
    $this->result = '';
    $callback = function ($ch, $str) use ($obj) {
        $obj->result .= strtoupper($str);
        return strlen($str);//return the exact length
    };
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
    curl_exec($ch);
    curl_close($ch);
    return $this->result;
}

To see how I used it, check out this link: Parallel cURL Request with WRITEFUNCTION Callback.

like image 116
Expedito Avatar answered Nov 05 '22 06:11

Expedito