我正在使用 PHP 的 cURL 函数从 steampowered.com 读取配置文件。检索到的数据是 XML,只需要前大约 1000 个字节。
我使用的方法是添加一个 Range header ,这是我在 Stack Overflow 答案 ( curl: How to limit size of GET? ) 上读到的。我尝试的另一种方法是使用 curlopt_range,但这也不起作用。
<?
$curl_url = 'http://steamcommunity.com/id/edgen?xml=1';
$curl_handle = curl_init($curl_url);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($curl_handle, CURLOPT_HTTPHEADER, array("Range: bytes=0-1000"));
$data_string = curl_exec($curl_handle);
echo $data_string;
curl_close($curl_handle);
?>
执行此代码时,它会返回全部内容。
我使用的是 PHP 版本 5.2.14。
最佳答案
服务器不接受 Range header 。你能做的最好的事情就是在你收到比你想要的更多的数据时立即取消连接。示例:
<?php
$curl_url = 'http://steamcommunity.com/id/edgen?xml=1';
$curl_handle = curl_init($curl_url);
$data_string = "";
function write_function($handle, $data) {
global $data_string;
$data_string .= $data;
if (strlen($data_string) > 1000) {
return 0;
}
else
return strlen($data);
}
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($curl_handle, CURLOPT_WRITEFUNCTION, 'write_function');
curl_exec($curl_handle);
echo $data_string;
也许更干净,你可以使用 http 包装器(如果它是用 --with-curlwrappers
编译的,这也会使用 curl)。基本上,您会在循环中调用 fread
,然后在您获得的数据多于您想要的数据时在流上调用 fclose
。如果禁用了 allow_url_fopen
,您还可以使用传输流(使用 fsockopen
而不是 fopen
打开流并手动发送 header )。
关于php - 无法限制 PHP 的 cURL 函数的下载大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431703/