This javascript function takes JSON and formats it to XML. The data is a long XML string, whic I would like to allow the user to download. I’m trying to use ajax to post the data to a php page wichi will create the file and then allow the user to download it.
json2xml(eval(data));
JS
$.ajax({
type: 'POST',
url: 'download/functions.php',
data: xml2,
dataType: XML
});
I have used this PHP function to write to a file, but I’m not sure how to now send the js variable to this function.
$data = $_POST['xml2'];
writetoxml($data, 'WF-XML'.$current. '.xml');
function writetoxml($stringData, $myFile) {
$current = date('m-d-Y-g-i-s');
$fh = fopen('download/'.$myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
download($file);
}
function downloadFile($file) {
if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/csv");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
exit;
}
}
This is currently returning a server 500 error.
Updated:
With your provided jQuery AJAX call:
Your PHP would look like this:
Try passing an object (in this case
{ key: value }into the data property of the$.ajaxcall so that you can reference it by your key. In this case our key isxmlso on the PHP side, we grab$_POST['xml']and that should give you the contents of xml2.The download code was taken from the PHP docs on readfile(). However, I still can’t help but think there is a better way to accomplish this.
I would HIGHLY recommend against allowing the user to effectively create a web accessible file containing whatever they want on your server. As aforementioned, a clarification of your general goal would be helpful. I think I understand what you’re trying to do but why you are doing it would be nice to know as there may be a better and safer way to accomplish the same result.