Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writting a file to specified location 1

Status
Not open for further replies.

sylve

Programmer
Jan 18, 2005
58
CA
I have php code that writes a xml file to a specific location. The code is really simple, called by a hyperlink.
Right now, it saves my file to my .php's directory.

I want the user to choose where he wants to save the file by means (hopefully) of Save As dialog box.
Here is a simplified sample of the writting code.

Code:
$file = fopen("$file_name","w");
	
//(code that fills $xml_buffer)
	
fwrite($file, $xml_buffer);
fclose($file);

I'm just starting php and javascript but i am willing to use any of those languages to get it done. Can anybody help me work out something that will let the user specify where he wants the file saved?
 
On his local machine would be best. This is for a intranet.
 
You have to stream the file down to the browser sending the appropriate headers - a 'forced' download. The browser handles the file save and location dialog.
 
How do you stream the file down to the browser? Is it different depending what browser the user is using?
Thanks for the help
 
i'm not aware of any x-browser incompatibility on basic file streaming.

assuming you have the contents of that which you wish to save as a long text string, you just set some headers and then echo the file. the headers tell the browser to treat it as a file download rather than something to display on the screen.

the headers might look like:
Code:
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/octet-stream");

the application/octet-stream is the key one. this tells the browser that it's something to "open or save".

if you are streaming a file that is on the server get the file size and add it to the header info by

Code:
header("Content-length: " .filesize ($path.$filename));

you would also stream a pre-existing file most easily with the command (after the headers):
Code:
readfile($path.$filename);
OR if your php implementation doesn't support readfile (pre php3 - unlikely...)
Code:
$fh = fopen($path.$filename,"rb");
fpassthru ($fh);

hth
Justin
 
I got my code to work by erasing the fopen, fwrite and fclose. Rayne, the header function helped.

header("Content-type: application/xml");
header("Content-Length: $len");
header("Content-Disposition: attachment; filename=" .$file_name);
print ($xml_buffer);

This prompts for a save then will open the buffer.

Thank you all for the help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top