无法限制PHP的cURL函数的下载大小 [英] Having trouble limiting download size of PHP's cURL function

查看:244
本文介绍了无法限制PHP的cURL函数的下载大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP的cURL函数从steampowered.com读取配置文件。检索的数据是XML,只需要大约1000个字节。

I'm using PHP's cURL function to read profiles from steampowered.com. The data retrieved is XML, and only the first roughly 1000 bytes are needed.

我使用的方法是添加一个Range标题,溢出回答( curl:如何限制GET的大小?)。我尝试的另一种方法是使用curlopt_range但是没有工作。

The method I'm using is to add a Range header, which I read on a Stack Overflow answer (curl: How to limit size of GET?). Another method I tried was using the curlopt_range but that didn't work either.

<?
$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);
?>

执行此代码时,它会返回整个事物。

When this code is executed, it returns the whole thing.

我使用PHP版本5.2.14。

I'm using PHP Version 5.2.14.

推荐答案

服务器不支持Range标题。您可以做的最好的是,一旦收到更多的数据,你想要取消连接。示例:

The server does not honor the Range header. The best you can do is to cancel the connection as soon as you receive more data than you want. Example:

<?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包装(这也将使用curl,如果它被编译 - with-curlwrappers )。基本上,你会在循环中调用 fread ,然后在流上有 fclose ,当你得到的数据超过你想要的数量。您也可以使用传输流(使用 fsockopen 打开流,而不是 fopen 并手动发送标头)if allow_url_fopen 已停用。

Perhaps more cleanly, you could use the http wrapper (this would also use curl if it was compiled with --with-curlwrappers). Basically you would call fread in a loop and then fclose on the stream when you got more data than you wanted. You could also use a transport stream (open the stream with fsockopen, instead of fopen and send the headers manually) if allow_url_fopen is disabled.

这篇关于无法限制PHP的cURL函数的下载大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆