2014-02-24 55 views
1

我想打印我的MySQL結果到XML。這是我迄今爲止所嘗試的:PHP的MySQL查詢結果到XML

include('dbconnect.php');

$sql = "SELECT verse_id, verse_title, verse_content, lang FROM verses WHERE lang = 'English'"; 
$stmt = $conn->prepare($sql); 
$stmt->execute(); 

$set = array(); 

while($r = $stmt->fetchAll(PDO::FETCH_ASSOC)){ 
    $set = $r; 
} 

$xml = new SimpleXMLElement('<root/>'); 
array_walk_recursive($set, array($xml, 'addChild')); 
print $xml->asXML(); 


?> 

但它顯示是這樣的:

<1>verse_id<27>verse_title<"Peace I leave with you; my peace I give you. I do not give to you as the world gives. Do not let your hearts be troubled and do not be afraid. >verse_contentlang<2> 

我要顯示這樣的:

<verse> 
<verse_id>1</verse_id> 
<verse_title>John 3:16</verse_title> 
<verse_content>For God so loved the world...</verse_content> 
<lang>English</lang> 
</verse> 

我不知道什麼是錯誤的,但如果你知道如何做到這一點,可以幫助,我會很感激。

回答

1

可以使用DOMDocument代替SimpleXMLElement和設定的formatOutputtrue值:

$doc = new DOMDocument('1.0', 'UTF-8'); 
$doc->formatOutput = true; 

<?php 

// "Create" the document. 
$xml = new DOMDocument("1.0", "UTF-8"); 
$xml->formatOutput = true; 

// Create some elements. 
$xml_album = $xml->createElement("Album"); 
$xml_track = $xml->createElement("Track", "The ninth symphony"); 

// Set the attributes. 
$xml_track->setAttribute("length", "0:01:15"); 
$xml_track->setAttribute("bitrate", "64kb/s"); 
$xml_track->setAttribute("channels", "2"); 

// Create another element, just to show you can add any (realistic to computer) number of sublevels. 
$xml_note = $xml->createElement("Note", "The last symphony composed by Ludwig van Beethoven."); 

// Append the whole bunch. 
$xml_track->appendChild($xml_note); 
$xml_album->appendChild($xml_track); 

// Repeat the above with some different values.. 
$xml_track = $xml->createElement("Track", "Highway Blues"); 

$xml_track->setAttribute("length", "0:01:33"); 
$xml_track->setAttribute("bitrate", "64kb/s"); 
$xml_track->setAttribute("channels", "2"); 
$xml_album->appendChild($xml_track); 

$xml->appendChild($xml_album); 
// Parse the XML. 
print '<pre>' . htmlentities($xml->saveXML()) . '</pre>'; 
?> 

輸出 enter image description here

+0

你能給我完整的答案嗎?對不起,我不明白這 – Dunkey

+0

有一個很好的例子http://ir1.php.net/domdocument#82447 ... – 2014-02-24 06:58:30

+0

我跟着這個例子,但它只是顯示沒有元素的記錄 – Dunkey