PHP DOM XML输出:缺少数据集

时间:2012-09-02 19:57:18

标签: php xml dom

使用MYSQL数据库上的php查询并使用DOM输出xml文件,一切正常,除非并非所有数据集都写入xml文件。例如。我可以列出预期结果的数量:

$num_results = mysql_num_rows($result);
echo $num_results;

例如20,但在保存的xml文件(“auswertung.xml”)中只存在19个条目。每次都不会写第一个数据集。可能有什么不对?

以下是相关的代码:

// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);

// Opens a connection to a mySQL server
$connection=mysql_connect ($dbhost, $username, $password);
if (!$connection) {
    die('Not connected : ' . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
}


$query = "SELECT * FROM Herpeto WHERE Art like '$Art' ORDER BY ID ASC";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
$num_results = mysql_num_rows($result);

// Iterate through the rows, adding XML nodes for each
echo $num_results;
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);

$newnode->setAttribute("Art", $row['Art']);
$newnode->setAttribute("Anzahl", utf8_encode ($row['Anzahl']));
$newnode->setAttribute("Status", $row['Status']);
$newnode->setAttribute("Stadt", utf8_encode($row['Stadt']));
$newnode->setAttribute("Fundstelle", utf8_encode($row['Fundstelle']));
$newnode->setAttribute("Bemerkung", utf8_encode($row['Bemerkung']));
$newnode->setAttribute("Tag", utf8_encode ($row['Tag']));
$newnode->setAttribute("Monat", utf8_encode ($row['Monat']));
$newnode->setAttribute("Jahr", utf8_encode ($row['Jahr']));
$newnode->setAttribute("Beobachter", utf8_encode($row['Beobachter']));
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}

$dom->save('auswertung.xml');

1 个答案:

答案 0 :(得分:1)

你在xml输出中得到20行中的19行,因为你在将结果调用mysql_fetch_array()之前将它传递给实际生成xml输出的while循环:

$row = mysql_fetch_array($result); // <-- here you get the first row
//...
while ($row = @mysql_fetch_assoc($result)){ // <-- now while loop starts from 2nd row