简体   繁体   中英

how to get files from web services and save them on our disk using php?

I could successfully connect to a web service, it provides a list of files that I need to save them on my disk, I am wondering how can I download and save them on my disk?

simple response is as following (response is shorten)

 <files>
   <file>
       <name>1.jpeg</name>
       <address>c:\photos\1.jpeg</address>
       <url>www.xxx.com\photos\1.jpeg</url>
   </file>
   <file>
       <name>my.pdf</name>
       <address>c:\pdfs\my.pdf</address>
       <url>www.xxx.com\pdfs\my.pdf</url>
  </file>
</files>

I've found the following but not sure how to save the $output

 function url_get_contents ($Url) {
     if (!function_exists('curl_init')){ 
          die('CURL is not installed!');
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $Url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $output = curl_exec($ch);
     curl_close($ch);
     return $output;
 }

I used the following but something is wrong, it create the file but its empty

$fp = fopen("lib\1",'x');
fwrite($f, $output);
fclose($fp);

Are the files offered by your web service publicly available and without authentication? If so, there are a heap of ways to get the files, providing you know their full locations...

You can use PHP's file_get_contents to grab the content of the file then save it somewhere...

$page = file_get_contents('NETWORK_ADDRESS\pdfs\my.pdf');

Or you can use CURL, take a look at the answer to this question , there is a full code example showing you how to download a file using CURL and PHP.

Or if your files are local (unlikely) to your PHP installation, you can use PHP's Copy function to move the file to where you want it. Read about copy here.

Once you have the file, lets assume in the $page variable as per my example above, use file_put_contents to save the contents of that file...

$file = 'filename.ext';
file_put_contents($file, $page);

More information on file_put contents here .

There are a heap of ways to do it, providing the file is accessible. Give us some more information and we can suggest a suitable solution.

You'll need to know the public url in order to download the files. In other words, how does anyone but the server access these files? What kind of web service is this? What protocol are you using? If it's publicly accessible, you can use file_get_contents to save the file. Otherwise, curl and some authentication will probably suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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