0

我正在尝试在我的网站上实施 Google 地图。我在这里学习教程:https ://developers.google.com/maps/articles/phpsqlajax_v3?hl=sv

但是,我在循环数据库时无法正确输出 xml。在本教程中有关于如何输出 xml 的三个示例。使用示例二和三时,我都收到“第 1 列第 2 行错误:文档末尾的额外内容”。

Som 这是怎么回事,为什么我会收到此错误消息。由于代码来自谷歌,我认为它是正确的,所以我最好的猜测是我的文件中有某种隐藏的符号。

非常感谢任何帮助!

<?php  

 require("dbinfo.php"); 

// 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 (localhost, $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());
} 

// Select all the rows in the markers table

$query = "SELECT * FROM markers WHERE 1"; 
$result = mysql_query($query);
if (!$result) {  
die('Invalid query: ' . mysql_error());
} 

header("Content-type: text/xml"); 

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){  
// ADD TO XML DOCUMENT NODE  
$node = $dom->createElement("marker");  
$newnode = $parnode->appendChild($node);   
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);  
$newnode->setAttribute("lat", $row['lat']);  
$newnode->setAttribute("lng", $row['lng']);  
$newnode->setAttribute("type", $row['type']);
} 
echo $dom->saveXML();
?>

编辑:

Here's an example of my output which might give some more insights on what's going on:

<marker name="Pan Africa Market" address="1521 1st Ave, Seattle, WA" lat="47.608940"      
lng="-122.340141" type="restaurant">
<marker name="Buddha Thai &amp; Bar" address="2222 2nd Ave, Seattle, WA"    
lat="47.613590" lng="-122.344391" type="bar">
<marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.624561"    
lng="-122.356445" type="restaurant">
</marker>
</marker>
</marker>
</marker>

所以问题似乎是每个循环的标记节点都没有关闭。相反,关闭节点只是在最后添加。

4

1 回答 1

1

您已经分配$node给顶部的标记节点,并且您正在 while 循环中覆盖它......这就是它在第一次迭代后搞砸的原因。用这个替换你的while循环:

<?php
while ($row = @mysql_fetch_assoc($result)){  
// ADD TO XML DOCUMENT NODE  
    $marker = $dom->createElement("marker");  
    $node->appendChild($marker);   
    $marker->setAttribute("name",$row['name']);
    $marker->setAttribute("address", $row['address']);  
    $marker->setAttribute("lat", $row['lat']);  
    $marker->setAttribute("lng", $row['lng']);  
    $marker->setAttribute("type", $row['type']);
}
?>

希望这可以帮助。

于 2012-07-05T07:04:15.253 回答