0

I have a web form that I want to save to an XML file and send the information as an email. But the code in some way feels repetitive. Is there any more efficient way?

webform.php

<!DOCTYPE html>
<html>
<head></head>
<body>   
<div class="content">
    <form action="formprocessor.php" method="POST">
        <label>Name: </label>
        <input name="name" type="text" size="25" />

        <label>Course: </label>
        <input name="course" type="text" size="25" />

        <label>Book: </label>
        <input name="book" type="text" size="255" />

        <label>Price: </label>
        <input name="price" type="text" size="7" />

        <label>Email: </label>
        <input name="email" type="text" size="255" />

        <label>Phone #: </label>
        <input name="phone" type="text" size="12" />

        <input name="mySubmit" type="submit" value="Submit!" />
    </form>
</div>
</body>
</html>

formprocessor.php

<?php
$name = $_POST["name"];
$course = $_POST["course"];
$book = $_POST["book"];
$price = $_POST["price"];
$email = $_POST["email"];
$phone = $_POST["phone"];

echo $name;
?>

First I need to define the name in the input.

Then the same name in the post formprocessor.php

Assign it to a variable

Use the variable to mail and XML

I have to do this 30 times (30 fields) with copy paste code but different name.

Anders
  • 11
  • 1
  • 5

1 Answers1

0

Here is an example of what you could do. I'd highly recommend building an array and working with that to build your xml instead of option 1 though: (see ie. How to convert array to SimpleXML)

// option 1
$_POST = [
    'foo' => 'bar',
    'bar' => 'foo'
    ];

foreach($_POST as $key => $value) {
    $$key = $value; // http://php.net/manual/en/language.variables.variable.php
}

var_dump($foo, $bar);

// option 2
$toXMLArray = [];   
foreach($_POST as $key => $value) {
    $toXMLArray[$key] = $value;
}

var_dump($toXMLArray);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($toXMLArray, array ($xml, 'addChild'));
print $xml->asXML();
steros
  • 1,794
  • 2
  • 26
  • 60
  • 2
    Why convert $_POST to an array and then convert the array to XML - it's simple enough to do this in 1 step. – Nigel Ren Jun 21 '18 at 06:54
  • Exactly! `$_POST` is already an array. In fact, you're just duplicating it into `$toXMLArray` in a totally redundant operation – Phil Jun 21 '18 at 06:55
  • it's just an example not knowing his requirements. he might want to work with the array, add/remove data, resort, or whatever. you shouldn't do that on the $_POST array. it is merely to show the different approaches. But sure if he just needs transform $_POST as is to xml you can skip that step. You're welcome to add that as option 3 :) – steros Jun 21 '18 at 06:58
  • _"you shouldn't do that on the $_POST array"_ <- why? – Phil Jun 21 '18 at 07:05
  • https://stackoverflow.com/questions/7433243/can-i-assign-a-value-to-a-post-variable-in-php – steros Jun 21 '18 at 07:11