2009-12-27 43 views
1

我需要從通過http訪問的非常大的遠程XML文件中檢索少量數據。我在開始時只需要文件的一部分,但我訪問的文件通常會很大,以至於全部下載都會導致超時。它似乎應該可能與fsockopen拉關閉連接之前只需要儘可能多,但沒有我試過的工作。PHP:希望fsockopen只檢索遠程xml文件的一部分

下面是我一直在嘗試的簡化版本。任何人都可以告訴我我需要做什麼改變嗎?

<?php 

$k = 0; 

function socketopen($funcsite, $funcheader){ 

$fp = fsockopen ($funcsite, 80, $errno, $errstr, 5); 

$buffer = NULL; 

if ($fp) { 

    fwrite($fp, "GET " . $funcheader . " HTTP/1.0\r\nHost: " . $funcsite. "\r\n\r\n"); 


while (!feof($fp)) { 
    $buffer = fgets($fp, 4096); 
    echo $buffer; 

    if($k == 200){ 
     break; 
    } 
    $k++; 
    } 

    fclose ($fp); 
    } else { 
    print "No Response:"; 
} 
return (html_entity_decode($buffer)); 
} 

$site = "www.remotesite.com"; 
$header = "/bigdatafile.xml"; 
$data = socketopen($site, $header); 
?> 

這工作正常,但總是打開並下載整個遠程文件。 (我實際上使用了不同於if($ k = x)的條件,但那應該不重要)。

任何幫助非常感謝。 -Jim

回答

0

與此代碼,你可以下載整個RSS

if (!$xml = simplexml_load_file("http://remotesite.com/bigrss.rss)) 
    { 
     throw new RuntimeException('Unable to load or parse feed'); 
    } 

    else 
    { 
    file_put_contents($xml,'mybigrss.rss'); 
    } 

,但如果你想獲得那麼就某些部分做了以下內容:

$limit = 512000; // set here a limit 
$sourceData = fread($s_handle,$limit); 

// your code ect.. 

或用EOF

$source=''; 
while (!feof($s_handle)) 
$source.=fread($s_handle,1024); // set limit 
+0

編輯:現在它:-) – richsage 2009-12-27 16:13:08

+0

利己工作?你用你的代碼試過了嗎? – streetparade 2009-12-27 16:20:56

+0

我仍然試圖做這項工作。它需要simplexml_load_file()還是我可以使用它與fsockopen? (這是一個問題,因爲一些XML並不總是很好的形成,但我可以用它作爲分隔數據,它不是一個RSS提要)。 Jim H. – 2009-12-27 17:49:36

4

任何理由不使用file_get_contents()呢?

$buffer = html_entity_decode(file_get_contents('http://www.remotesite.com/bigdatafile.xml', 0, null, $offsetBytes, $maxlenBytes)); 

你只需要指定$offsetBytes$maxlenBytes


試試這個:

set_time_limit(0); 

echo $buffer = html_entity_decode(file_get_contents('http://www.remotesite.com/bigdatafile.xml', 0, null, 1024, 4096)); 
+0

刪除我的答案,並upvoted你的,因爲這是解決問題的最好方法之一。 – 2009-12-27 16:24:42

+0

確定第一我也想用file_get_contents(),但我沒有:( – streetparade 2009-12-27 16:26:16

+0

這是有道理的,但是當我嘗試它時,我仍然得到在發生任何事情之前下載的整個文件大文件仍然超時有什麼我需要做? Jim H. – 2009-12-27 17:46:45