【发布时间】:2013-11-25 21:29:34
【问题描述】:
我正在尝试使用 php 从 html 表单创建这样的 XML。我想创建复杂的元素
<recipe>
<portion_size>
<portion_num>
</portion_num>
</portion_size>
<recipe_description>
<prep_time>
</prep_time
<recipe descrip>
</recipe descrip>
<recipe_description>
类似的东西,但是我似乎无法使用 DOM 正确嵌套它,这是我的 php 代码。有人有什么建议吗?
$doc = new DOMDocument(); //open the object xml
$r = $doc->createElement("recipe");
$doc->appendChild($r);
$name = $doc->createElement('name',$name);
$r->appendChild($name);
$r = $doc->createElement("portion_size");
$doc->appendChild($r);
$child = $doc->createElement('portion_num',$portionNum);
$r->appendchild($child);
$prepTime = $doc->createElement('prep_time',$prepTime);
$r->appendChild($prepTime);
$recipeDescrip = $doc->createElement('descrip',$recipeDescrip);
$r->appendChild($recipeDescrip);
$utensilNum = $doc->createElement('utensil_num',$utensilNum);
$r->appendChild($utensilNum);
$utensilDescrip = $doc->createElement('utensil_descrip',$utensilDescrip);
$r->appendChild($utensilDescrip);
$quantityAmount = $doc->createElement('quantity_amount',$quantityAmount);
$r->appendChild($quantityAmount);
$ingredientName = $doc->createElement('ingredient_name',$ingredientName);
$r->appendChild($ingredientName);
$stepNum = $doc->createElement('step_num',$stepNum);
$r->appendChild($stepNum);
$stepDetail = $doc->createElement('step_detail',$stepDetail);
$r->appendChild($stepDetail);
【问题讨论】:
-
我认为它适用于我的份量大小,但是它不会在 part_num 之后关闭它,而是在 xml 末尾关闭它
-
只用 DOM 来创建 xml 是“正确的方法”,但它也非常痛苦。您最好将其全部构建为一个巨大的字符串
$xml = "<recipe><foo><bar /></foo></recipe";并继续处理更重要的事情。 -
这可能会导致更多的工作。您必须注意转义并确保 xml 格式正确。
标签: javascript php xml