我正在尝试在我的网站上实施Google地图。我在这里遵循教程:https://developers.google.com/maps/articles/phpsqlajax_v3?hl=sv
但是,在循环数据库时,我无法正确输出xml。在本教程中,有三个关于如何输出xml的示例。在使用示例二和三时,我得到“第1列第2行的错误:文档末尾的额外内容”。
Som是怎么回事,为什么我收到此错误消息。由于代码来自Google我认为它是正确的,所以我最好的猜测是我在我的文件中有一些隐藏的标志。
任何帮助都非常赞赏!
<?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 & 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>
所以问题似乎是标记节点没有为每个循环关闭。而是在结尾添加结束节点。
答案 0 :(得分: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']);
}
?>
希望这有帮助。