Skip to content
Advertisement

Export array to XML file – problem with utf-8 encoding

I want to export an array to XML file in PHP:

$fxml = fopen('file.xml', 'w');
$xml = new SimpleXMLElement('<postal_codes/>');

$rows = $db->query('SELECT * FROM postal_codes ORDER BY ID');

foreach ($rows as $row) {
  if ($provinces[$row['region']] == 'test') {
    $place = $xml->addChild('place');
    foreach($fields as $key => $val) {
      $place->addChild($val, $row[$val]);
    }
  }
}

fwrite($fxml, $xml->asXML());
fclose($fxml);

The data is exported, but the values don’t contain Polish characters such as: ń, ś, ł, ó etc. How to fix this? Instead of correct characters, I have: ś ń ę

Advertisement

Answer

That is because you load an ASCII XML document. If you provide the UTF-8 encoding it will not encode the unicode characters.

$data = "Witaj świecie";

$xml = new SimpleXMLElement("<postal_codes/>");
$xml->addChild("place", $data);

echo $xml->asXML();

$xml = new SimpleXMLElement(
    "<?xml version='1.0' encoding='utf-8'?>n<postal_codes/>"
);
$xml->addChild("place", $data);

echo $xml->asXML();

Output:

<?xml version="1.0"?>
<postal_codes><place>Witaj świecie</place></postal_codes>
<?xml version="1.0" encoding="utf-8"?>
<postal_codes><place>Witaj świecie</place></postal_codes>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement