简体   繁体   中英

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

你能在例子中描述一下吗?

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 .

Have a look at

CALLBACK OPTIONS for definition and

The callbacks.php Example

It is used with curl_setopt function.

CURLOPT_WRITEFUNCTION is the name of a callback function where the callback function takes two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be written by using this callback function. Must return the exact number of bytes written or this will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM