php執行抓取網頁的幾種方式

一、遠程php代碼:

<?php
    header('access-allow-origin:*');
    sleep(1);
    echo "hello\n";
    echo "world";

二、具體實現:

  1. file函數:
    a. 代碼:
    <?php
    $url = 'http://localhost/test.php';
    $output = file($url);
    var_dump($output);

    b. 輸出:

    array(2) {
    [0]=>
    string(6) "hello"
    [1]=>
    string(5) "world"
    }
  2. file_get_contents函數:
    a. 代碼:
    <?php
    $url = 'http://localhost/test.php';
    $output = file_get_contents($url);
    var_dump($output);

    b. 輸出:

    string(11) "hello world"
  3. fopen函數:
    a. 代碼:
    <?php
    $url = 'http://localhost/test.php'; 
    $handle = fopen($url,"rb");
    do{     
            $data = fread($handle,1024);     
            if(strlen($data)==0) {
                    break;   
            }     
            $output = $data;
    }  
    while(true);
    fclose($handle);
    var_dump( $output);

    b. 輸出:

    string(11) "hello world"
  4. curl函數:
    a. 代碼:
    <?php
    $url = 'http://localhost/test.php'; 
    $ch = curl_init();
    $timeout = 1;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $output = curl_exec($ch);
    curl_close($ch);
    var_dump($output);

    b. 輸出:

    string(11) "hello world"
  5. fsockopen函數:
    a. 代碼:
    <?php
    $url = 'localhost/test.php'; 
    $fp = fsockopen($url, 80, $errno, $errstr, 30);
    if (!$fp) {
            echo "$errstr ($errno)<br />\n";
    } else {
        stream_set_blocking($fp,0);
            $out = "GET / HTTP/1.1\r\n";
            $out .= "Host: {$url}\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fp, $out);
            while (!feof($fp)) {
                    var_dump(fgets($fp, 128));
            }
            fclose($fp);
    }

    b. 輸出:

    string(11) "hello world"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章