2012-02-06 103 views
0

我使用此代碼搜索來自網站的鏈接。如何從鏈接下載文件?

<?php 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,"http://example.com"); 
curl_setopt($ch, CURLOPT_TIMEOUT, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
$result=curl_exec ($ch); 
curl_close ($ch); 

// search the results from the starting site 
if($result){ 
    preg_match_all('/<a href="(http:\/\/www.[^0-9]+.pdf?)"/', $result, $output, PREG_SET_ORDER); 
    foreach($output as $item ){ 
     print_r($item); 
     } 
} 
copy($item, 'file.pdf'); 
?> 

只是一個pdf閱讀鏈接。那麼我需要一個代碼來下載PDF文件,通過在PHP中的鏈接提供。複製功能不起作用。 謝謝:)

+0

不知道我明白你的問題的權利。你想把所有找到的pdf作爲下載發送到瀏覽器? – Oldskool 2012-02-06 08:25:49

+0

@Oldskool我想從網上的鏈接下載所有的PDF文件,並保存在我的電腦文件夾。謝謝 – bruine 2012-02-06 08:28:21

回答

1

我已經解決了這個問題,使用此代碼,非常感謝您@Oldskool :):

<?php 
set_time_limit(0); 
include 'simple_html_dom.php'; 
$url='example.com'; 
//set your save path here 
$path = '/home/igos/pdfs/'; 

$html = file_get_html($url) or die ('invalid url'); 
foreach($html->find('a') as $e) { 
    $link= $e->href; 
    if (preg_match('/\.pdf$/i', $link)) { 
      $result[] = $link; 
      copy($link, $path . basename($link)); 
    } 
} 

?> 
1

有兩個問題在這裏:

  1. 你只是你的foreach循環內打印,不保存任何內容。
  2. 您正在使用copy()函數,其靜態文件名爲file.pdf

你可能會想,以節省您的foreach循環中,並用相同的名稱或一些隨機的(否則,每個保存操作將覆蓋以前的file.pdf),像這樣的所有文件:

// Set your save path here 
$path = '/home/igos/pdfs/'; 

foreach($output as $item){ 
    copy($item, $path . basename($item)); 
    } 

這將保存所有的文件,保持其原始文件名/home/igos/pdfs/文件夾。

+0

我試過了,瀏覽器發出警告:basename()期望參數1是字符串,給定的數組 – bruine 2012-02-06 08:57:09

+0

@igos您將不得不使用包含實際文件名的變量(這應該從' print_r($ item)'輸出)。這可能類似於'$ item [0]'。 – Oldskool 2012-02-06 09:11:29

+0

你能幫我一步一步來嗎?首先,我需要抓取PDF擴展的鏈接。我提出新的問題[http://stackoverflow.com/questions/9187865/find-link-in-pdf-extension] – bruine 2012-02-08 04:33:14