2015-05-18 12 views
2

我有此表的XML文件...使用PHP創建從SQL表中的數據

rss(
    id serial, 
    title varchar(25) not null, 
    link text not null, 
    description TEXT not null, 
    imagename text 
); 

...我試圖創建使用PHP存儲的數據的XML文件。

$db = mysqli_connect("localhost", "root", "", "s3382313"); 
$q = 'select * from rss'; 
$run = mysqli_query($db, $q); 

if($run && mysqli_num_rows($run)) { 
    $doc = new DOMDocument('1.0'); 
    $doc->formatOutput = true; 
    $doc->preserveWhiteSpace = true; 

    $root = $doc->createElement('data'); 
    $doc->appendChild($root); 

    while(($fetch = mysqli_fetch_assoc($run))!== false) { 
     $node = $doc->createElement('node'); 
     $root->appendChild($node); 

     foreach($fetch as $key => $value) { 
      createNodes($key, $value, $doc, $node); 
     } 
    } 
    $doc->save("thexmlfile.xml"); 
} 

function createNodes($key, $value, $doc, $node) { 
    $key = $doc->createElement($key); 
    $node->appendChild($key); 
    $key->appendChild($doc->createTextNode($value)); 
} 

我收到此錯誤:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\WeatherRadar\process_XML.php on line 27

線27:foreach($fetch as $key => $value) {

我該怎麼辦?

+0

你應該檢查變量$ fetch。什麼print_r($ fetch);正在輸出? – Vindic

+0

Array([id] => 1 [title] => test rss [link] => test.link [description] => test description [imagename] => IMG_1667.jpg) – EJackson

回答

0

我認爲你的$fetch被限制在一個太多的括號內,它目前只是測試while條件的有效性。

while((true != false)) { 
    //... 
} 

因此,改寫太:

while($fetch = mysqli_fetch_assoc($run)) { 
    /** $fetch will be scoped for the loop now **/ 
} 

其次進行調試,重要的是檢查之前$fetch內容以迭代它,因爲它可能不是一個嵌套的結果集。

+0

用上面的代碼,獲取輸出是'Array([id] => 1 [title] => test rss [link] => test.link [description] => test description [imagename] => IMG_1667.jpg)' – EJackson

+0

'提取輸出爲'1'仍然具有相同的錯誤 – EJackson

+0

@EJackson刪除'!== false',因爲一旦'$ run'迭代到最後,while將停止。 – MackieeE