XML Encoding - with examples

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Okay,

After much iconv, headers and "workarounds" I figured I can't use
DOMDocument for XMLs when under ISO-8859-1 encoding without messing accented
chars.

The idea is simple: get a query result and turn into a XML. Using
mysql_fetch_object is the best way for this task.

If I just do nothing: get iso text, insert into the XML and not set the
encoding, the XML loads (w/o xml content type in header) but it's a bad
thing to do (not all browsers like this).

Anyone have any ideas why the following doesn't work or how to fix it?


The "right" thing to do, which doesn't work.

<?php
header('Content-type: text/xml; charset = ISO-8859-1');

$unidades = listarUnidadesSetor(58,1); //returns a stdClass -
mysql_fetch_object

$doc = new DOMDocument("1.0", 'ISO-8859-1'); //setting XML Encoding to ISO
breaks in the first accented char
$doc->formatOutput = true;  //Figured this does nothing

$xml = $doc->createElement( "unidades" ); //root element
$doc->appendChild( $xml );

foreach ($unidades as $unidade)
{
  $valores = get_object_vars($unidade); //all object atributes (row
name/value in mysql table)

  $unidade = $doc->createElement( "unidade" );
  foreach ($valores as $atributo=>$valor){
//    $valor = iconv('ISO-8859-1','UTF-8',$valor); // iconv messes with
accented chars
    $node = $doc->createElement( $atributo );
    $node->appendChild(
    $doc->createTextNode( $valor )
    );
    $unidade->appendChild( $node );
  }
  $xml->appendChild( $unidade );
}
$doc->appendChild( $xml );
echo $doc->saveXML();
?>

The "wrong" thing, which correctly gives me the xml file with correct
encoding and everything (just built it myself as a string, no DOM functions
are used):
<?php
header('Content-type: text/xml; charset = ISO-8859-1');

$unidades = listarUnidadesSetor(58,1);

$xml  = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
$xml .= "<unidades>\n";
foreach ($unidades as $unidade){
    $xml .= "<unidade>\n";
    $valores = get_object_vars($unidade);
    foreach ($valores as $atributo=>$valor){
    $xml .= "<$atributo> $valor </$atributo>";
    }
    $xml .= "</unidade>\n";
}
$xml .= "</unidades>\n";

echo $xml;
?>


Regards,
-- 
Thiago Henrique Pojda

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux