xml generator script wordpress [closed]

Merry Christmas!

First off, this works but you should never use this in production code – this should only get you pointed in the right direction. Second, the form redirect to itself but you might want to use a Custom Endpoint in WordPress or a simple AJAX call. Before using any info supplied by the user make sure you sanitize everything – Read up on Data Sanitization and Validation With WordPress.

I also threw in an option to have the file downloaded automatically or display in the browser window. If you want to force the download, make sure the ‘Content-disposition’ header is set.

Cheers!

<?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();
}