从PHP生成XML时解析属性时出错

时间:2017-08-20 14:29:23

标签: php mysql xml google-maps

我试图通过使用MySQL中的数据在我的网站上实现谷歌地图但最终得到此错误

  

此页面包含以下错误:

     第18行第1行的

错误:错误解析属性名称

     

下面是第一个错误之前的页面呈现。

以下是由https://developers.google.com/maps/documentation/javascript/mysql-to-maps

提供的代码

我可以知道导致错误的原因吗?

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

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}

// 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");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // Add to XML document node
  echo '<marker ';
  echo 'id="' . $ind . '" ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>

1 个答案:

答案 0 :(得分:1)

看起来这个例子是错误的。

echo 'id="' . $ind . '" ';

应该是

echo 'id="' . $row['id'] . '" ';

(未尝试从mysql_fetch_assoc调用中删除错误抑制以查看数据库是否抛出错误。即删除@

无论是哪种情况,都会发生这种情况。

您正在输出XML文档,正在呈现文档 - 但是您得到了

  第18行第1行的

错误:错误解析属性名称

因为XML在name attribute处格式不正确 - 这会告诉我你几乎肯定在XML输出中有一个php错误。

e.g。

<markers>
    <marker id="Notice: Undefined variable: "id" in ~\whatever\kml.php on line blah blah blah
" name="foo" address="bar" ... />}

您可以通过curl或类似方式调用文件,或通过&#34;查看源&#34;来确认这一点。在大多数浏览器中。

最后,如果情况不是这样,那么请在打开php标签后立即尝试在文件顶部打开错误报告,例如

<?php
ini_set('display_errors', 1);
error_reporting(~0);

然后再次检查脚本的实际输出。