I am working on a project where I am seeking to provide an HTML form where users can enter values in form inputs, which would then be added to an XML file on submit.
So far, I have found examples of how to do this, but only at one level of XML data, for example a form with an input for "name" that submits to an XML file like the following:
<meals><type>breakfast</type></meals>
Or perhaps like this:
<meals>
<meal>
<type>breakfast</type>
</meal>
</meals>
I am seeking to use forms to write XML node content at an additional level, such as:
<meals>
<meal>
<type>breakfast</type>
<ingredients>
<ing>eggs</ing>
</ingredients>
</meal>
<meal>
<type>dinner</type>
<ingredients>
<ing>pork chop</ing>
</ingredients>
</meal>
</meals>
I have a form that provides for input of these elements, and a PHP script that writes them to an XML document, but I am not sure how to iterate over the nested arrays respective of their parent elements. When I submit the data above, the XML that I get is like the following:
<meals>
<meal>
<type>breakfast</type>
<ingredients>
<ing>eggs</ing>
<ing>pork chop</ing>
</ingredients>
</meal>
<meal>
<type>dinner</type>
<ingredients>
<ing>eggs</ing>
<ing>pork chop</ing>
</ingredients>
</meal>
</meals>
In other words, my PHP script creates an array of meals, and an array of ingredients, but I am wondering if there is a way to create nested arrays of meal>ingredients, or meal[i]ingredients.
Edit to add code for the HTML form and PHP script:
The HTML form:
<form>
<input name="done" value="done" type="submit">
<fieldset name="meal">
type: <input name="type[]" type="text">
<br>
Ingredients
<fieldset name="ingredients">
ing. name: <input name="ingName[]" type="text">
</fieldset>
</fieldset>
<fieldset name="meal">
type: <input name="type[]" type="text">
<br>
Ingredients
<fieldset name="ingredients">
ing. name: <input name="ingName[]" type="text">
</fieldset>
</fieldset>
</form>
There is JS that allows for adding additional meal s and ingredient inputs.
Here is the PHP script:
if(isset($_REQUEST['done']))
{$xml = new DOMDocument("1.0","UTF-8");
$xml->load("groceries4.xml");
$rootTag=$xml->getElementsByTagName("groceries")->item(0);
$mealTypes=$_REQUEST['type'];
foreach($mealTypes as $mt)
{$mealTag=$xml->createElement("meal");
$mealType=$xml->createElement("type",$mt);
$mealTag->appendChild($mealType);
$ingrsTag=$xml->createElement("ingredients");
$mealTag->appendChild($ingrsTag);
$mealIngs=$_REQUEST['ingName'];
foreach($mealIngs as $mi)
{$ingTag=$xml->createElement("ing",$mi);
$ingrsTag->appendChild($ingTag);};
$rootTag->appendChild($mealTag);};
$xml->save("groceries4.xml");
}
?>