[英]Getting a file via CURL Posting Data
我有一個Web服務,您將數據發布到該Web服務,它返回一個txt.gz文件。 我正在嘗試使用cURL發布信息,但是我不確定如何准備和處理返回給我的文件以供下載。
我得到了成功的回應; 但該文件為0 KB,並且顯然沒有下載。 任何幫助將不勝感激!
這是我目前正在做的事情:
$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);
您永遠不會寫入文件。
您需要將結果寫入文件。
fwrite($fp, $result);
您最好使用file_put_contents
,然后不需要打開/關閉文件。
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.
}
但是也許在兩者之間使用$ result來檢查請求實際上是可以的,然后再將其保存到文件中。
您應該檢查curl_exec()
的返回curl_exec()
$result = curl_exec($ch);
if ($result === false) {
echo 'Curl error: ' . curl_error($ch);
}
將false
寫入文件會導致文件為空,所以這可能正在發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.