Ben Hathaway
Ben Hathaway

Reputation: 356

Create XML structure with PHP from HTML form

I am creating a system where a user can enter an ingredient and then save its quantity, I use PHP to save it as XML.

It currently saves like this.

 <ingredients>
    <ingredient quantity="2">Apple</ingredient>
    <ingredient quantity="4">Banana</ingredient>
  </ingredients>

Instead i would like to save it like this but i can't figure out how.

  <ingredient>
            <quantity_amount>2</tns:quantity_amount>
            <quantity_name>teaspoons</tns:quantity_name>
            <ingredient_name>baking powder</tns:ingredient_name>
        </ingredient>

for each ingredient added

Here is my PHP and HTML i currently use.

HTML

  <div id="addIngredient">
                <p>
                <input type="text" id="ingredient_1" name="ingredient[]" value="" placeholder="Ingredient"/>
                <input type="text" id="quantity_1" name="quantity[]"  value="" placeholder="Quantity"/>
                <a href="#" id="addNewIngredient">Add</a>
                </p>

                </div>

PHP

// Start for loop, from 0 to ingredientName
for ($i = 0; $i < count($ingredientName); $i++) {
    // Select current item
    $element = $ingredientName[$i];

    // Updated used ingredients list ONLY
    // if the ingredient wasn't added yet
    $temp = search($upIngreds, 'value', $element);
    if (empty($temp)) {
        $upIngreds[] = array('value' => $element, 'label' => $element, 'image' => 'images/products/default.jpg');
    }

    // Select current item quantity
    $qty = $quantity[$i];
    // Create ingredient element and fill with $element
    $ingredient = $xml->createElement('ingredient', $element);
    // Set quantity attiribute to $qty value
    $ingredient->setAttribute('quantity', $qty);
    // Append it to ingredients element
    $ingredients->appendChild($ingredient);
}

Upvotes: 0

Views: 185

Answers (1)

michi
michi

Reputation: 6625

to create a new ingredient according to your desired XML structure:

// creating the document and its root
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('ingredients','');
$dom->appendChild($root);

// create new ingredient and link it to root 
$ingredient = $dom->createElement('ingredient','');
$root->appendChild($ingredient);    

// create children and link them to ingredient
$q_amount = $dom->createElement('quantity_amount',"1");
$q_name = $dom->createElement('quantity_name',"spoon");
$i_name = $dom->createElement('ingredient_name',"PHP");
$ingredient->appendChild($q_amount);
$ingredient->appendChild($q_name);
$ingredient->appendChild($i_name);

echo $dom->saveXML();

see it working: https://eval.in/85654

Be sure to sanitize user input from your form prior to inserting it into the XML.

Upvotes: 1

Related Questions