2012-04-09 83 views
0

我使用file_get_contents在線閱讀JSON URL 更快的方式PHP和我沒有安裝任何cURL建議如何使我的要求更快在線閱讀JSON文件中

感謝, 馬里亞納

+0

也許從服務器的響應速度很慢?你可以做的事情不多。你可以緩存數據,所以你不必爲每個請求進行外部呼叫? – AndrewR 2012-04-09 15:28:16

回答

0

確實沒有辦法讓您的請求更快。如果數據變化不大,你可以做的就是在本地緩存數據。

僞代碼:

if (get_modification_time_of_file('cached.json') < time() - 300) { 
    download_file() 
} else { 
    read_locally() 
} 
0

您有2個選項。

1:通過使用則fopen /的file_get_contents功能(多個)

2:通過設置一個客戶端網橋併發送它通過使用AJAX POST方法到PHP。然後使用json_decode在PHP上獲取它。

1

做一些簡單的標杆:

<?php 
$start = microtime(true); 
for ($i=0;$i<=10;$i++){ 
    $handle = fopen("http://example.com/", "r"); 
    while (!feof($handle)) { 
     $result .= fread($handle, 1024); 
    } 
    fclose($handle); 
} 
$end = microtime(true); 
$time = $end - $start; 

echo "Did fopen test in $time seconds<br />\n"; 
?> 

難道的fopen試驗6.1602981090546秒

<?php 
//file_get_contents is basically a wrapper for the above fopen so hence not much of a difference 
$start = microtime(true); 
for ($i=0;$i<=10;$i++){ 
    $result = file_get_contents('http://example.com'); 
} 
$end = microtime(true); 
$time = $end - $start; 

echo "Did file_get_contents test in $time seconds<br />\n"; 
?> 

的file_get_contents有沒有在6.5289459228516秒

<?php 
$start = microtime(true); 
for ($i=0;$i<=10;$i++){ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, "http://example.com"); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    $result = curl_exec($ch); 
} 
$end = microtime(true); 
$time = $end - $start; 

echo "Did cUrl test in $time seconds<br />\n"; 
?> 
測試

難道cUrl作者試驗2.9657130241394秒

捲曲勝手了......時間去尋找更好的主機