XML character encoding problem with PHP

I have some code that generates XML, my only problem is encoding words like á, olá and ção.
These characters do not display correctly, and when I try to read the XML, I get an error related to that character.

$dom_doc = new DOMDocument("1.0", "utf-8");
$dom_doc->preserveWhiteSpace = false;
$dom_doc->formatOutput = true;
$element = $dom->createElement("hotels");

while ($row = mysql_fetch_assoc($result)) {

$contact = $dom_doc->createElement( "m" . $row['id'] );

$nome = $dom_doc->createElement("nome", $row['nome'] );

$data1 = $dom_doc->createElement("data1", $row['data'] );
$data2 = $dom_doc->createElement("data2", $row['data2'] );


$contact->appendChild($nome);
$contact->appendChild($data1);
$contact->appendChild($data2);

$element->appendChild($contact);
$dom_doc->appendChild($element);

      

What can I change to fix my problem I am using utf-8 ???

+3


source to share


2 answers


You are using utf-8, an 8-bit Unicode encoding format. While it correctly supports all 1,112,064 Unicode codes, it is possible that there is a problem here.
Try UTF-16 as standard, just an idea. See below:

$dom_doc = new DOMDocument("1.0", "utf-16");

      



OR

$dom_doc = new DOMDocument("1.0", "ISO-10646");

      

0


source


Please try to put right in '<3 →' ',' olá 'or' ção '.

$data1 = $dom_doc->createElement("data1", 'ção');

      

If you have no problem, this is probably the data you are getting from mysql that is not encoded correctly. Are you sure your mysql is outputting correct UTF-8?

To know this, make your PHP dump your data into an HTML document with the meta tag set to UTF-8 and see if the characters are displayed correctly.



You can also call:

$data1 = $dom_doc->createElement("data1", mb_detect_encoding($row['data']));

      

and see what encoding PHP detects for your data.

If you are unable to convert data from your database or change your settings, you can use mb_convert to do this on the fly: http://www.php.net/manual/en/function.mb-convert-encoding.php

+1


source







All Articles