fsockopen无阻塞 批量抓取页面、图片,批量采集

function multiFsockopen($urlArr) {
    $sockets = array ();
    $urlInfo = array ();
    $retDone = array ();
    $retData = array ();
    $errno = array ();
    $errstr = array ();
    $urlNum = count ( $urlArr );
    for($x = 0; $x < $urlNum; $x ++) {
        $urlInfo [$x] = parse_url ( $urlArr [$x] );
        $urlInfo [$x] ['port'] = (isset ( $urlInfo [$x] ['port'] )) ? $urlInfo [$x] ['port'] : 80;
        $urlInfo [$x] ['path'] = ($urlInfo [$x] ['path']) ? $urlInfo [$x] ['path'] : "/";
        $sockets [$x] = fsockopen ( $urlInfo [$x] ['host'], $urlInfo [$x] ['port'], $errno [$x], $errstr [$x], 30 );
        stream_set_timeout ( $sockets [$x], 60 );
        stream_set_blocking ( $sockets [$x], false );
        $query = (isset ( $urlInfo [$x] ['query'] )) ? "?" . $urlInfo [$x] ['query'] : "";
        fwrite ( $sockets [$x], "GET " . $urlInfo [$x] ['path'] . "$query HTTP/1.0\r\nHost: " . $urlInfo [$x] ['host'] . "\r\nConnection: close\r\n\r\n" );
    }
    $done = false;
    while ( ! $done ) {
        for($x = 0; $x < $urlNum; $x ++) {
            if (! feof ( $sockets [$x] )) {
                if (isset ( $retData [$x] )) {
                    $retData [$x] .= fgets ( $sockets [$x], 128 );
                } else {
                    $retData [$x] = fgets ( $sockets [$x], 128 );
                }
            } else {
                $retDone [$x] = 1;
            }
        }
        $done = (array_sum ( $retDone ) == $urlNum);
    }
    return array_combine ( $urlArr, $retData );
}

$results = multiFsockopen ( array (
        'http://www.baidu.com/img/bdlogo.gif',
        'http://a.tbcdn.cn/tbsp/img/header/logo.png',
        'http://gtms01.alicdn.com/tps/i1/T1N0pxFEhaXXXxK1nM-357-88.jpg',
        'http://p9.qhimg.com/t01a6b838b555a7435b.png' 
) );
//http://my.oschina.net/cart/
foreach ( $results as $key => $result ) {
    file_put_contents ( basename ( $key ), substr ( $result, strpos ( $result, "\r\n\r\n" ) + 4 ) );
}
exit ();


fsockopen socket 无服务器限制 支持header、cookie、refer 挂马远程

CURL和fsockopen两种方式POST数据并写入文件

你可能感兴趣的:(fsockopen,批量采集,无阻塞,批量抓取页面、图片)