2011-05-10 99 views
1

我想要從網頁下載圖像,例如www.yahoo.com,並使用PHP將其存儲在文件夾中。使用PHP cURL下載多個圖像

我使用file_get_contents()獲取頁面源並提取img src標記。我通過這個src到cURL的代碼。該代碼不會給出任何錯誤,但圖像不會被下載。請檢查代碼。我不明白我出錯的地方。

<?php 
    $html = file_get_contents('www.yahoo.com'); 
    $ptn = '/< *img[^>]*src *= *["\']?([^"\']*)/i'; 
    preg_match_all($ptn, $html, $matches, PREG_PATTERN_ORDER); 
    $seq = 1; 
    foreach($matches as $img) 
    { 
     $fp = fopen("root/Images/image_$seq.jpg", 'wb'); 
     $ch = curl_init ($img); 
     curl_setopt($ch,CURLOPT_FILE, $fp); 
     curl_setopt($ch,CURLOPT_URL, $img); 
     curl_setopt($ch, CURLOPT_HEADER, 0); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 
     $image = curl_exec($ch); 
     curl_close($ch); 
     fwrite($fp, $image); 
     fclose($fp); 
     $seq++; 
    } 
    echo "IMAGES DOWNLOADED"; 
?> 

回答

0
  • 爲$的img圖像的全URL
  • 圖像是否受保護(使用referer)?

    $image = false; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_REFERER,$url); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 7); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch,CURLOPT_ENCODING,gzip); 
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 
    $image = curl_exec ($ch); 
    

嘗試調試第一。

先用雅虎的單張圖片http://www.depers.nl/beeld/w100/2011/201105/20110510/anp/sport/img-100511-349.onlinebild.jpg試一下。

另外,爲什麼使用file_get_contents和curl?改用curl。

  1. 爲cURL創建功能:function simple_curl ($url,$binary=false){ set your cURL vars, return curl_exec)
  2. 獲取yahoo.com:多陣列:$result = simple_curl($url);
  3. 與模式(檢查匹配包含完整的URL(域名+目錄+文件)
  4. 每個循環模式匹配(不要忘了得到的鏈接! !於是就$matches[1]環)
  5. 捲曲的二進制文件,並將其保存:$image = simple_curl($match,true);
0
  • www.yahoo.com是不是一個URL,http://www.yahoo.com/
  • $ img是一個需要迭代的數組$matches[1]
  • 您都告訴cURL寫入文件並檢索結果。使用一個。

我不知道你怎麼看不到錯誤。我會研究這一點。複製並粘貼,然後運行它給了我很多錯誤。

1
foreach($matches as $img) 

應改爲

foreach($matches[1] as $img) 

BTW:你應該通過更換的捲曲的file_get_contents,它的3倍左右的速度;)