PDA

View Full Version : Output mySQL data as XML with PHP



phodges
May 9th, 2009, 02:04 PM
Hi

After reading the article "Output mySQL data as XML with PHP" here:

http://www.kirupa.com/web/mysql_xml_php.htm

I am trying to go one step further and have the result loop through the column names and dynamically create the XML tags. It doesn't seem to work and for the life of me I cannot work out why.

The problem seems to be with this line:

$xml_output .= "\t\t<" . $colName . ">" . $nodeData . "</" . $colName . ">\n";

Because if I take out the closin node it works, but just produces badly formed XML. If I put the closing node in it produces nothing.

Any help would be appreciated:

<?php

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

$host = "localhost";
$user = "root";
$pass = "root";
$database = "dddd";

$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");

$query = "SELECT * FROM listing";
$resultID = mysql_query($query, $linkID) or die("Data not found.");

$colLength = mysql_num_fields($resultID);

$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<data>\n";

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){

$row = mysql_fetch_assoc($resultID);
$xml_output .= "\t<listings>\n";

for($y = 0 ; $y < $colLength ; $y++){

$colName = mysql_field_name($resultID, $y);

$nodeData = $row[$colName];

$nodeData = str_replace("&", "&amp;", $nodeData);
$nodeData = str_replace("<", "&lt;", $nodeData);
$nodeData = str_replace(">", "&gt;", $nodeData);
$nodeData = str_replace("\"", "&quot;", $nodeData);

$xml_output .= "\t\t<" . $colName . ">" . $nodeData . "</" . $colName . ">\n";

}

$xml_output .= "\t</listings>\n";

}

$xml_output .= "</data>";

echo $xml_output;

?>

dzeno
May 10th, 2009, 05:55 AM
<?PHP

$link = mysql_connect("localhost","db_name","password");
mysql_select_db("db_table_in_wich_is_your_data");

$query = 'SELECT * FROM listing';
$results = mysql_query($query);


echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "<Listing_xml>\n";

while($line = mysql_fetch_assoc($results))

{
echo "<listing>\n";
echo "<data><![CDATA[" . $line["listing"] . "]]></data>\n";
echo "</listing>\n";
}

echo "</Listing_xml>\n";

mysql_close($link);

?> That's it

phodges
May 11th, 2009, 05:28 AM
Thanks for replying.

I did actually managed to get my script to work. Turns out it was actually a memory issue with my php.ini and once I reset the time_out settings it worked fine.