圣诞快乐!
首先,这是可行的,但您永远不应该在生产代码中使用它-这只能让您指向正确的方向。其次,表单重定向到自身,但您可能希望使用Custom Endpoint 在WordPress或简单的AJAX 呼叫在使用用户提供的任何信息之前,请确保已清理所有内容-阅读Data Sanitization and Validation With WordPress.
我还加入了一个选项,可以让文件自动下载或显示在浏览器窗口中。如果要强制下载,请确保设置了“Content disposition”标题。
干杯
<?php
// check the method against post action method
// we\'re looking for POST xml and GET form
if($_SERVER[\'REQUEST_METHOD\'] === \'POST\') render_xml();
else if( $_SERVER[\'REQUEST_METHOD\'] === \'GET\') render_form();
die();
function render_form(){ ?>
<!DOCTYPE html>
<html>
<body>
<form action="<?php $_SERVER[\'REQUEST_URI\']; ?>" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
Custom:<br>
<input type="text" name="custom" value="12345">
<br><br>
<input type="submit" name="submit" value="GET RESULT">
<input type="submit" name="download" value="DOWNLOAD">
</form>
</body>
</html>
<?php
}
function render_xml(){
header(\'Content-type: text/xml\');
if(!empty($_REQUEST[\'download\'])){
// Force download -- checks the \'name\' of the submit button for contents
$filename = \'the_awesome_file.xml\';
header("Content-disposition: attachment; filename=\\"$filename\\"");
}
?><?xml version="1.0" encoding="UTF-8"?>
<root>
<firstname><?php echo $_POST[\'firstname\']; ?></firstname>
<lastname><?php echo $_POST[\'lastname\']; ?></lastname>
<custom><?php echo $_POST[\'custom\']; ?></custom>
</root><?php die();
}