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
  • 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 stackoverflow.com/a/5112417/465183 Commented Aug 25, 2013 at 16:09

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Panagiotis i' ll try it and info you.
Just make sure to save the $xml var to a file, for example with file_put_contents("myXMLfile.xml, $xml);
It works fine. And it is a perfect way without add an extra load for memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.