0

I try to find a solution by extracting sql table values in utf8 encoding but no luck. The bellow code exports a right XML file named "test.xml" but without encoding. Any suggestions?

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$dbname = "My_DB";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$sql = "SELECT product_id, model, image  FROM product";
$q = mysql_query($sql)or die(mysql_error()); 


$xml = "<products>";
while($r = mysql_fetch_array($q)){

  $xml .= "<product>";

 $xml .= "<id>";  
 $xml .= "<![CDATA[".$r["product_id"]."]]>";
 $xml .= "</id>";
 $xml .= "<name><![CDATA[" . $r["model"] . "]]></name>";
 $xml .= "<image>".$r['image']."</image>";   
 $xml .= "</product>";  
}

$xml .= "</products>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML("test.xml");

?>
  • 1
    Don't know which DB you are using, but `mysql` have the `--xml` switch to output in XML. You should consider taking a look to this SO thead too http://stackoverflow.com/a/5112417/465183 – Gilles Quénot Aug 25 '13 at 16:09

1 Answers1

0

What you are doing here is adding all data in a variable and then just outputting it to a file. Why don't you try formatting your XML file as you want it (instead of using SimpleXMLElement only in the end? What I mean is something like this:

[...]
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xml .= "<products>";
while($r = mysql_fetch_array($q)){

  $xml .= "<product>";

 $xml .= "<id>";  
 $xml .= "<![CDATA[".$r["product_id"]."]]>";
 $xml .= "</id>";
 $xml .= "<name><![CDATA[" . $r["model"] . "]]></name>";
 $xml .= "<image>".$r['image']."</image>";   
 $xml .= "</product>";  
}

$xml .= "</products>";

echo $xml;

This will result to an XML file created on your own. Just saying because you are not using the SimpleXMLElement all the way, instead you are adding the XML elements and attributes manually. You can take a look at here to see how else you could have built your file!

Hope it helps!

Panagiotis
  • 309
  • 2
  • 13