PHP - 使用 fopen 加载(非常)长
PHP - (very) long loading with fopen
使用 fopen 句柄时,加载时间变得非常长。准确地说是10秒左右。
$handle = fopen("http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}", "r");
if (FALSE === $handle) {
echo "Failed";
exit("Failed to open stream to URL");
}
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 32);
}
以上是我正在使用的代码。
这是一种低效的方法吗?如果是这样,有效的方法是什么?
我也把这些结果爆出来打印出来。但即使去掉结果部分的打印,加载时间也没有改变。
如果您使用其他方式进行 http 请求,也许可以加快速度。
您可以使用 cURL:
$url = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
curl_close($c);
或通过以下方式尝试:
$contents = file_get_contents( "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}" );
使用 fopen 句柄时,加载时间变得非常长。准确地说是10秒左右。
$handle = fopen("http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}", "r");
if (FALSE === $handle) {
echo "Failed";
exit("Failed to open stream to URL");
}
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 32);
}
以上是我正在使用的代码。 这是一种低效的方法吗?如果是这样,有效的方法是什么?
我也把这些结果爆出来打印出来。但即使去掉结果部分的打印,加载时间也没有改变。
如果您使用其他方式进行 http 请求,也许可以加快速度。
您可以使用 cURL:
$url = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
curl_close($c);
或通过以下方式尝试:
$contents = file_get_contents( "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player={$pname}" );