0

当我运行以下函数时,它会按预期检索 HTML,但 WRITEFUNCTION 回调没有显示任何生命迹象。没有回显,变量 $this->test_output 保持不变。

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;
}
4

1 回答 1

0

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

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;
}
于 2013-04-11T19:34:07.330 回答