我正在创建一个用户可以输入成分然后保存数量的系统,我使用PHP将其保存为XML。
它目前会像这样保存。
<ingredients>
<ingredient quantity="2">Apple</ingredient>
<ingredient quantity="4">Banana</ingredient>
</ingredients>
相反,我想像这样保存它,但我无法弄清楚如何。
<ingredient>
<quantity_amount>2</tns:quantity_amount>
<quantity_name>teaspoons</tns:quantity_name>
<ingredient_name>baking powder</tns:ingredient_name>
</ingredient>
添加每种成分
这是我目前使用的PHP和HTML。
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);
}
答案 0 :(得分:1)
根据您所需的XML结构创建新成分:
// 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();
看到它有效:https://eval.in/85654
确保在将表单中的用户输入插入XML之前对其进行清理。