2

I am a beginner in PHP and XML.

Can somebody tell me how to include XML encoding when I write a new xml file.

Here are the codes:

writexml.php

<?php 
 $ids =  array("1", "2", "3", "4", "5");
 $names = array("Jean Claude Van Damme", "Scott Adkins", "Dolph Ludgren", "Michael Jai White", "Michael Worth");

 $domdoc = new DOMDocument(); 
 $domdoc->formatOutput = true; 

 $el_actionstars = $domdoc->createElement( "actionstars" ); 
 $domdoc->appendChild( $el_actionstars  ); 

 $arr_size = count($ids);

 for ($i=0; $i < $arr_size; $i++) {
  $el_actionstar = $domdoc->createElement( "actionstar" ); 

  $el_id =  $domdoc->createElement( "id" ); 
  $el_id->appendChild( $domdoc->createTextNode($ids[$i] . "")); 
  $el_actionstar->appendChild($el_id);

  $el_name =  $domdoc->createElement( "name" ); 
  $el_name->appendChild( $domdoc->createTextNode($names[$i] . "")); 
  $el_actionstar->appendChild($el_name);


  $el_actionstars->appendChild($el_actionstar);
 }

 echo $domdoc->saveXML(); 
 $domdoc->save("actionstars.xml") 
?>

The xml output is <?xml version="1.0"?> and I want to add the encoding to make it look like <?xml version="1.0" encoding="ISO-8859-1"?>. Pls help...

Newbie Coder
  • 10,684
  • 19
  • 41
  • 53
  • [Duplicate](http://stackoverflow.com/questions/869650/getting-simplexmlelement-to-include-the-encoding-in-output) – Félix Saparelli May 31 '11 at 07:07
  • The example for [DOMDocument::__construct](http://de3.php.net/manual/en/domdocument.construct.php) shows how to do that. Please refer to the manual before asking questions with obvious answers. – Gordon May 31 '11 at 07:16
  • Lol. Someone inject more love... – tofutim May 31 '11 at 07:19

3 Answers3

5

Try using this in your instantiation:

/**
 * <?xml version="1.0" encoding="UTF-8" ?>
 */
$domdoc = new DOMDocument('1.0', 'UTF-8');

As seen here: http://php.net/manual/en/domdocument.construct.php

Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
Robert Heine
  • 1,820
  • 4
  • 29
  • 61
4

See bottom of http://php.net/manual/en/domdocument.savexml.php

When you save whole document: DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node: DOMDocument->saveXML(DOMNode) produces always string in UTF-8.

You can set it in the constructor

DOMDocument::__construct ([ string $version [, string $encoding ]] )

e.g.,

$domdoc = new DOMDocument('1.0', 'iso-8859-1');
tofutim
  • 22,664
  • 20
  • 87
  • 148
1

Try with new DomDocument('1.0', 'UTF-8');

RRStoyanov
  • 1,162
  • 1
  • 13
  • 23