XML Encoding - with examples

From: Date: Tue, 29 Jul 2008 18:33:38 +0000
Subject: XML Encoding - with examples
Groups: php.general 
Request: Send a blank email to php-general+get-277429@lists.php.net to get a copy of this message
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

« previous php.general (#277429) next »