1

尝试使用 curl_multi_init 获取页面信息。但是当我尝试使用 curl_multi_getcontent() 获取信息时 - 30 秒后的页面。下。我应该如何正确使用 curl_multi_getcontent()?谢谢

class Grab
{
    public function getData()
    {
        $sessions = array('111', '222', '333', '444', '555');

        $handle = curl_init();

        foreach($sessions as $sId) {
            $sessionId = $sId;

            echo $sessionId.'<br/>';

            $url = 'https://www.mypage.com?id='.$sessionId.'&test=1';

            curl_setopt($handle, CURLOPT_URL, $url);
            curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($handle, CURLOPT_FRESH_CONNECT, false);
            curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($handle, CURLOPT_FAILONERROR, true);

            $sResponse = $this->curlExecWithMulti($handle);
        }
    }

    function curlExecWithMulti($handle) {
        // In real life this is a class variable.
        static $multi = NULL;

        // Create a multi if necessary.
        if (empty($multi)) {
            $multi = curl_multi_init();
        }

        // Add the handle to be processed.
        curl_multi_add_handle($multi, $handle);

        // Do all the processing.
        $active = NULL;
        do {
            $ret = curl_multi_exec($multi, $active);
        } while ($ret == CURLM_CALL_MULTI_PERFORM);     

        while ($active && $ret == CURLM_OK) {
            if (curl_multi_select($multi) != -1) {
                do {
                    $mrc = curl_multi_exec($multi, $active);

                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }

        **$res = curl_multi_getcontent($handle); // - very slow**
        $this->printData($res);

        // Remove the handle from the multi processor.
        curl_multi_remove_handle($multi, $handle);

        return TRUE;
    }

    public function printData($res)
    {
            $oPayment = json_decode($res);

            var_dump($oPayment);
            var_dump($errorno);
            echo '<br/>---------------------<br/>';
    }
}

$grab = new Grab;
$grab->getData();
4

1 回答 1

1

您不应该在 foreach 循环中为每个 $handle 调用 curlExecWithMulti。您应该创建句柄数组,通过 curl_multi_add_handle 添加它们,然后才进行所有处理(curl_multi_exec 循环)。处理完成后,您可以使用 curl_multi_getcontent 循环读取所有结果。

它看起来像:

    $handles = array();

    foreach($sessions as $sId) {
        $handle = curl_init();
        $sessionId = $sId;

        echo $sessionId.'<br/>';

        $url = 'https://www.mypage.com?id='.$sessionId.'&test=1';

        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_FRESH_CONNECT, false);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($handle, CURLOPT_FAILONERROR, true);

        $handles[] = $handle;
    }

    // calling curlExecWithMulti once, passing array of handles
    // and got array of results
    $sResponse = $this->curlExecWithMulti($handles);
于 2013-10-26T18:43:55.093 回答