Germaine Chen
Germaine Chen

Reputation: 21

Encoding Error in PHP script to generate XML

I'm having problems with my PHP file that generates XML from MySQL database. The code is below

<?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>';

?>

I'm not sure what the problem is, but I have changed all my character encodings (in mysql and under htaccess) to UTF8. The problem surfaced recently after a server maintenance by my host, and I did not change my file before and after it, so I doubt that it could be a problem with my code itself. Can anyone point me in the right direction? Thanks in advance!

Upvotes: 2

Views: 466

Answers (1)

Rohit Choudhary
Rohit Choudhary

Reputation: 2269

You can use DomDocument class. I think what you are using is an old way. Please loo at following link.

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

Upvotes: 1

Related Questions