From what I can see wp_remote_get() saves remote file contents to memory.
The files that I need to download are compressed in either ZIP or GZIP and within which will either be a CVS or XMl file
What I need to do first is download the remote file to the harddrive as ZIP either GZIP and then unzip them
Is it possible to use wp_remote_get() to download the whole file and save it to a directory?
A non-Wordpress solution I used before was cURL:
public function grab_file($url, $new_file) {
//get file
$ch = curl_init();
$fp = fopen(DIR_PATH."zip/$new_file", "w");
$options = array(CURLOPT_URL => $url, CURLOPT_HEADER => 0, CURLOPT_FAILONERROR =>
1, CURLOPT_AUTOREFERER => 1, CURLOPT_BINARYTRANSFER => 1, CURLOPT_RETURNTRANSFER =>
1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_TIMEOUT => 5, CURLOPT_FILE => $fp);
curl_setopt_array($ch, $options);
$file = curl_exec($ch);
curl_close($ch);
fclose($fp);
if (!$file) {
//$error = "cURL error number:" . curl_errno($ch);
//$error .= "cURL error:" . curl_error($ch);
return false;
} else {
return true;
}
}
Well here’s the solution that I came up with:
Dealing with a GZIP file was a bit different:
So in conclusion. When you use wp_remote_get() to retrieve a remote file use the inbuilt PHP file functions to then save it where you want to. If you have a solution that utilizes WordPress functions then please post it up.
Althoug this question is from a few years back, since it pops up in Google as one of the first results, I thought I’d give a better suggestion to write
wp_remote_get()
‘s response to a file.The beginning is good, but the OP uses
fopen()
andfwrite()
to write the file, while that’s not necessary:In some cases
$wp_filesystem
isn’t accessible. In which case you can create a function to get it: