cURL写功能未被调用 [英] cURL WRITEFUNCTION not Being Called

查看:174
本文介绍了cURL写功能未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的函数,它检索HTML的预期,但WRITEFUNCTION回调没有显示生命的迹象。没有任何东西被重复,变量$ this-> test_output保持不变。

When I run the following function it retrieves the HTML as expected, but the WRITEFUNCTION callback shows no signs of life. Nothing gets echoed, and the variable $this->test_output remains unchanged.



function get_headers($urls){
    $curly = array();
    $result = array();
    $mh = curl_multi_init();
    $obj = $this;
    $test = function ($ch, $str) use ($obj){
        echo '<p class="red">--Hello World--</p>';
        $obj->test_output = 'Hello World';
        return strlen($str);
    };
    foreach ($urls as $key => $url) {
        $curly[$key] = curl_init();
        curl_setopt($curly[$key], CURLOPT_URL,            $url);
        curl_setopt($curly[$key], CURLOPT_HEADER,         0);
        if (is_callable($test)){
            curl_setopt($curly[$key], CURLOPT_WRITEFUNCTION, $test);
        } else {
            echo '<p class="red">--FUNCTION NOT VALID--</p>';
        }
        curl_setopt($curly[$key], CURLOPT_RETURNTRANSFER, 1);
        curl_multi_add_handle($mh, $curly[$key]);
    }
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while($running > 0);
    foreach($curly as $key => $cnt) {
        $content = curl_multi_getcontent($cnt);
        curl_multi_remove_handle($mh, $cnt);
        if (strlen($content) > 0){
            $result[$key] = $content;
        } else {
            curl_multi_close($mh);
            return FALSE;
        }
    }
    curl_multi_close($mh);
    echo "<pre class='red'>";
    print_r($this->test_output);
    echo "</pre>";
    return $result;
}


推荐答案

看起来cURL小车。我写了一个更简单的函数,发现WRITEFUNCTION只有当它是最后一个选项被指定时才被调用。当我将该行放在任何其他选项之前时,它被忽略:

It looks like cURL is a little buggy. I wrote a simpler function and found that the WRITEFUNCTION only gets called when it is the last option to be specified. When I placed that line before any of the other options, it was simply ignored:

function get_html(){
    $url = 'http://www.example.com';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $str){return -1;});
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

这篇关于cURL写功能未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆