PHP 脚本中的编码错误以生成 XML


Encoding Error in PHP script to generate XML

我的PHP文件从MySQL数据库生成XML时遇到了问题。代码如下

<?php
require("decibelone_dbinfo.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 location 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 '<name>' . parseToXML($row['name']) . '</name>';
    echo '<address>' . parseToXML($row['address']) . '</address>';
    echo '<latitude>' . $row['latitude'] . '</latitude>';
    echo '<longitude>' . $row['longitude'] . '</longitude>';
    echo '<description>' . $row['description'] . '</description>';
    echo '<time>' . $row['time'] . '</time>';
    echo '</marker>';
}
// End XML file
echo '</markers>';
?>

我不确定问题是什么,但我已将所有字符编码(在 mysql 和 htaccess 下)更改为 UTF8。这个问题最近在我的主机维护服务器后浮出水面,我之前和之后都没有更改我的文件,所以我怀疑这可能是我的代码本身的问题。谁能指出我正确的方向?提前感谢!

您可以使用

DomDocument类。我认为您正在使用的是旧方法。请点击以下链接。

http://php.net/manual/en/class.domdocument.php