简体   繁体   English

通过CURL发布数据获取文件

[英]Getting a file via CURL Posting Data

I have a web service which you post data to and it returns you a txt.gz file. 我有一个Web服务,您将数据发布到该Web服务,它返回一个txt.gz文件。 I'm trying to use cURL to post up the information, however I'm not sure how to be ready and handle the file which comes back at me to download. 我正在尝试使用cURL发布信息,但是我不确定如何准备和处理返回给我的文件以供下载。

I'm getting a successful response; 我得到了成功的回应; but the file is 0 KB, and obviously isn't downloading. 但该文件为0 KB,并且显然没有下载。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Here is currently what I'm doing: 这是我目前正在做的事情:

$url = 'http://www.mywonderfulurl.com';
$fields = array('id'=>'123');
$fields_string = 'id=123';
$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";

$ch = curl_init();

// set user agent
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

curl_setopt($ch, CURLOPT_TIMEOUT, 250);
curl_setopt($ch, CURLOPT_FILE, 'download.txt.gz');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if (file_put_contents('download.txt.gz', curl_exec($ch)) === false) {
        // Handle unable to write to file error.
        echo('you failed');
        exit;
    }



echo curl_getinfo( $ch, CURLINFO_HTTP_CODE );
//close connection
curl_close($ch);

You are never writing to the file. 您永远不会写入文件。

You need to write the result to file. 您需要将结果写入文件。

fwrite($fp, $result);

You are probably better off using file_put_contents , then you don't need to open/close the file. 您最好使用file_put_contents ,然后不需要打开/关闭文件。

http://php.net/manual/en/function.file-put-contents.php http://php.net/manual/zh/function.file-put-contents.php

if ($file_put_contents('download.txt.gz', curl_exec($ch)) === false) {
    // Handle unable to write to file error.
}

But maybe using the $result in between to check the request was actually ok before saving it to file. 但是也许在两者之间使用$ result来检查请求实际上是可以的,然后再将其保存到文件中。

You should check the return from curl_exec() 您应该检查curl_exec()的返回curl_exec()

$result = curl_exec($ch);
if ($result === false) {
    echo 'Curl error: ' . curl_error($ch);
}

Writing false to a file would result in an empty file, so this could be whats happening. false写入文件会导致文件为空,所以这可能正在发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM