我正在尝试使用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);
答案 0 :(得分:2)
你不应该使用DOMDocument :: createElement()的第二个参数,它不是w3c dom api的一部分而且似乎已经坏了。您需要使用DOMDocument :: createTextNode()。但是这有点吵,所以我建议你把这个工作封装成一个方法。
class MyDOMElement extends DOMElement {
public function appendElement($name, array $attributes = NULL, $content = '') {
$node = $this->ownerDocument->createElement($name);
if (!empty($attributes)) {
foreach ($attributes as $key => $value) {
$node->setAttribute($key, $value);
}
}
if (!empty($content)) {
$node->appendChild($this->ownerDocument->createTextNode($content));
}
$this->appendChild($node);
return $node;
}
}
class MyDOMDocument extends DOMDocument {
public function __construct($version = '1.0', $encoding= 'utf-8') {
parent::__construct($version, $encoding);
$this->registerNodeClass('DOMElement', 'MyDOMElement');
}
}
$dom = new MyDOMDocument();
$dom->appendChild($root = $dom->createElement('recipe'));
$root->appendElement('name', NULL, 'Reciepe Example');
$root
->appendElement('portion_size')
->appendElement('portion_num', NULL, '4');
$description = $root->appendElement('recipe_description');
$description->appendElement('prep_time', array('unit' => 'minutes'), '10');
//...
echo $dom->saveXml();
输出:
<?xml version="1.0" encoding="utf-8"?>
<recipe>
<name>Reciepe Example</name>
<portion_size>
<portion_num>4</portion_num>
</portion_size>
<recipe_description>
<prep_time unit="minutes">10</prep_time>
</recipe_description>
</recipe>