从PHP / MySQL查询创建XML时出现编码错误

时间:2014-11-07 18:44:50

标签: php mysql xml rss

我有以下代码成功查询并从MySQL动态导出到XML输出。我现在唯一的问题是我遇到编码错误,我不知道如何追踪它?

以下是一个示例网址:http://progresstechnologies.com/xml/xmlExport.php

代码

//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "bb";
$config['mysql_pass'] = "bb";
$config['db_name']    = "db";
$config['table_name'] = "table";

//connect to host
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
//select database
@mysql_select_db($config['db_name']) or die( "Unable to select database");

$xml          = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s"; //fruits
$xml         .= "<$root_element>";

//select all items in table
$sql = "SELECT * FROM table WHERE ListOfficeName LIKE 'Premier%' ";

$result = mysql_query($sql);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

if(mysql_num_rows($result)>0)
{
   while($result_array = mysql_fetch_assoc($result))
   {
      $xml .= "<".$config['table_name'].">";

      //loop through each key,value pair in row
      foreach($result_array as $key => $value)
      {
         //$key holds the table column name
         $xml .= "<$key>";

         //embed the SQL data in a CDATA element to avoid XML entity issues
         $xml .= "<![CDATA[$value]]>";

         //and close the element
         $xml .= "</$key>";
      }

      $xml.="</".$config['table_name'].">";
   }
}

//close the root element
$xml .= "</$root_element>";

//send the xml header to the browser
header ("Content-Type:text/xml");

//output the XML data
echo $xml;

1 个答案:

答案 0 :(得分:1)

您的数据库/表/列似乎使用了MySQL的默认latin1字符集。

解决方案1:如果您希望XML在latin1中,您可以通过更改

来解决问题
header ("Content-Type:text/xml");

header ("Content-Type: text/xml; charset=latin1");   

解决方案2:如果您想要UTF-8中的XML,请使用

将MySQL表的latin1列修改为UTF8
ALTER TABLE tblname MODIFY fldname TEXT CHARACTER SET utf8;

注意:如果您想在MySQL数据库中默认使用UTF-8而不是latin1 charset,请阅读:http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html