通过PHP将MySQL表中的数据转换为XML

时间:2012-07-01 05:08:59

标签: php mysql xml

  

可能重复:
  Headers already sent by PHP

我正在尝试遵循本教程:

  

Creating a Store Locator with PHP, MySQL & Google Maps
   Google Geo API小组;   2009年8月

我已经达到了一个MySQL表位置数据的地步。为了我的目的,我在本教程中更改了代码的元素。我只是想从MySQL表中提取所有数据并将其转换为XML,因此可以通过Google Maps API读取。

不幸的是,当我运行下面的代码时,浏览器页面不会加载并收到以下错误:

  

警告:无法修改标题信息 - 已在第43行的... / getdata / genxml.php中发送的输出(输出从... / getdata / genxml.php:8开始)

这可能是有问题的一行:

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

这是整个代码块。我犯了什么错误?谢谢!

<?php
require("phpsqlsearch_dbinfo.php");

//Get parameters from URL
//$center_lat = $_GET["lat"];
//$center_lng = $_GET["lng"];

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

// Search the rows in the markers table
$query = sprintf("SELECT * FROM markers WHERE 1");
$result = mysql_query($query);

$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}
// **Below is line 42. The error may be here.** 
header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("marker");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("id", $row['id']);
  $newnode->setAttribute("address", $row['address']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['lng']);
  $newnode->setAttribute("bt", $row['bt']);
  $newnode->setAttribute("dt", $row['dt']);
  $newnode->setAttribute("br", $row['br']);
  $newnode->setAttribute("bth", $row['bth']);
  $newnode->setAttribute("sqft", $row['sqft']);
  $newnode->setAttribute("lp", $row['lp']);
  $newnode->setAttribute("url", $row['url']);
  $newnode->setAttribute("dom", $row['dom']);
}
echo $dom->saveXML();

?>

2 个答案:

答案 0 :(得分:1)

当您已经发送了要输出的内容然后尝试发出对header()的调用时,会给出您发布的错误。

Something 在header()调用之前输出了一些东西,你需要找到它。它可能位于phpsqlsearch_dbinfo.php源文件中,也可能位于<?php标记之上,这是一个常见的错误。 (或者可能在<?php标记之上或在phpsqlsearch_dbinfo.php中的?>标记之后。)

我之前看到的另一个问题是某些编辑器没有正确翻译换行符和回车符,这可能是个问题。如果您在记事本中编辑文件,请使用支持换行和回车的其他编辑器,例如PSPad(免费软件)或UltraEdit(商业),并确保文件已保存在Unix格式中,不是 DOS格式。或者如果你在Unix命令提示符下使用类似vim的东西编辑它,如果你的源代码中有额外的回车符,那么很明显。

但就像我说的那样,当您尝试进行header()调用时,该错误明确告诉您某些已经输出到浏览器。 header()调用仅在以前没有任何内容(除了可能的其他header()调用之外)时才合法,包括任何空格或html标记。

答案 1 :(得分:0)

删除<?php代码

之前的所有空格和字符