2011-12-10 43 views
1

此代碼只附加for語句中的最後一個整數。我試圖爲for語句中的每個值附加$ root_text。 $ root_text應該是一個數組?我只追加1個值和$根 - >的appendChild($ root_text)appendChild使用foreach語句

代碼:

<?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(); 
?> 

回答

1

你目前每一次循環,保持(最終追加)只能從最後一次迭代的節點分配一個新值$root_text。爲什麼不直接在循環中直接使用appendChild

for($i = 1; $i <= 10; $i++) { 
    $test = $doc->createElement('test'); 
    $test->appendChild($doc->createTextNode($i)); 
    $root->appendChild($test); 
} 
+0

這仍然不會創建for語句中每個值的測試標記。 –

+0

@RPM - 我沒有意識到這是一項要求。只要在循環體中做這個部分。看我的編輯。 –

+0

我在哪裏陳述這個陳述?我收到一個錯誤:調用未定義的函數appendChild() –

-2

你在做什麼有一個與$ doc->一個createTextNode($更換$ 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(); 
?> 
+0

我剛剛測試了你的代碼。它輸出一個數組,但不會將它們作爲XML文檔中的節點追加。 –

+0

這是錯誤:可捕獲的致命錯誤:傳遞給DOMNode :: appendChild()的參數1必須是DOMNode的實例,第15行中的C:\ xampp \ htdocs \ append_child.php中給出的數組 –