我正在使用while循环创建XML,但是现在我需要在生成的XML之前加上XML标头信息和包装器标签,但我正努力使其正常工作,这是我的代码,
$result = mysql_query("SELECT * FROM users") or die(mysql_error()); $row = mysql_fetch_array($result); while ($row = mysql_fetch_array($result)) { $pumaXML = "<userDetails>"; $pumaXML .= "<userID>".$row['uid']."</userID>"; $pumaXML .= "<userName>".$row['userName']."</userName>"; $pumaXML .= "<points>".$row['points']."</points>"; $pumaXML .= "<imageURL>".$row['imageURL']."</imageURL>"; $pumaXML .= "<thumbURL>".$row['thumbURL']."</thumbURL>"; $pumaXML .= "</userDetails>"; };
我似乎找不到解决方法,我也尝试制作一个函数,但是效果并不理想,这里是代码,
function createXML($result) { while ($row = mysql_fetch_array($result)) { $pumaXML = "<userDetails>"; $pumaXML .= "<userID>".$row['uid']."</userID>"; $pumaXML .= "<userName>".$row['userName']."</userName>"; $pumaXML .= "<points>".$row['points']."</points>"; $pumaXML .= "<imageURL>".$row['imageURL']."</imageURL>"; $pumaXML .= "<thumbURL>".$row['thumbURL']."</thumbURL>"; $pumaXML .= "</userDetails>"; }; return $pumaXML; };
提前感谢!
这是使用DOM的方法:
function createUserDetailsXml(array $result) { $dom = new DOMDocument; $dom->formatOutput = TRUE; // enable automatic indenting $dom->loadXML('<users/>'); // set root node foreach($result as $row) { // create user-details node $user = $dom->createElement('user-details'); // create and append details to user-details node $user->appendChild( $dom->createElement('user-id', $row['uid'])); $user->appendChild( $dom->createElement('user-name', $row['userName'])); $user->appendChild( $dom->createElement('user-points', $row['points'])); $user->appendChild( $dom->createElement('image-url', $row['imageURL'])); $user->appendChild( $dom->createElement('thumb-url', $row['thumbURL'])); // add user-details node to XML document, e.g. users node $dom->documentElement->appendChild($user); }; return $dom->saveXML(); // returns the formatted XML };
请注意,该函数希望您传递完整的结果数组,因此我可以使用以下方法进行测试:
$result = array( array( 'uid' => 1, 'userName' => 'Gordon', 'points' => PHP_INT_MAX, 'imageURL' => 'http://example.com/gordon.jpg', 'thumbURL' => 'http://example.com/t_gordon.jpg' ), array( 'uid' => 2, 'userName' => 'John <blink>"Frigging"</blink> Doe', 'points' => 0, 'imageURL' => 'http://example.com/johndoe.jpg', 'thumbURL' => 'http://example.com/t_johndoe.jpg' ) ); echo createUserDetailsXml($result);
该函数将返回
<?xml version="1.0"?> <users> <user-details> <user-id>1</user-id> <user-name>Gordon</user-name> <user-points>2147483647</user-points> <image-url>http://example.com/gordon.jpg</image-url> <thumb-url>http://example.com/t_gordon.jpg</thumb-url> </user-details> <user-details> <user-id>2</user-id> <user-name>John <blink>"Frigging"</blink> Doe</user-name> <user-points>0</user-points> <image-url>http://example.com/johndoe.jpg</image-url> <thumb-url>http://example.com/t_johndoe.jpg</thumb-url> </user-details> </users>
请注意,DOM自动为您转义了John Doe名称中的特殊字符。DOM还将确保XML元素名称(或属性,如果使用它们)在语法上是有效的。它还添加了XML Prolog。