此代码仅附加for语句中的最后一个整数。我正在尝试为for语句中的每个值附加$ root_text。 $ root_text应该是一个数组吗?我只用$ root-> appendChild($ root_text)
附加1个值代码:
<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');
$root = $doc->createElement('test');
$doc->appendChild($root);
for($i = 1; $i <= 10; $i++) {
$root_text = $doc->createTextNode($i);
}
$root->appendChild($root_text);
print $doc->saveXML();
?>
答案 0 :(得分:1)
您每次通过循环时都会向$root_text
分配一个新值,仅保留(并最终附加)最后一次迭代中的节点。为什么不直接在循环中appendChild
?
for($i = 1; $i <= 10; $i++) {
$test = $doc->createElement('test');
$test->appendChild($doc->createTextNode($i));
$root->appendChild($test);
}
答案 1 :(得分:-2)
你正在做的是在每个周期用$ doc-&gt; createTextNode($ i)替换$ root_text。 您可能想要做的是使$ root_text成为一个数组。
<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');
$root = $doc->createElement('test');
$doc->appendChild($root);
$root_text = array(); //always initialize arrays
for($i = 1; $i <= 10; $i++) {
$root_text[] = $doc->createTextNode($i);
}
//this will output the contents of $root_text so you can examine it
print_r($root_text);
$root->appendChild($root_text);
print $doc->saveXML();
?>