[英]PHP mysql query result to xml
我想將mysql結果打印到xml。 到目前為止,這是我嘗試過的:
包括( '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>
我不知道出了什么問題,但是如果您知道該怎么做並且可以提供幫助,我將不勝感激。
您可以使用DOMDocument代替SimpleXMLElement
並將formatOutput
的值設置為true
:
$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>';
?>
產量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.