2011-05-31 59 views
2

我是PHP和XML的初学者。在PHP中包含XML编码

有人可以告诉我如何在编写新的xml文件时包含XML编码。

这里是代码:

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") 
?> 

XML输出是<?xml version="1.0"?>,我想补充的编码使它看起来像<?xml version="1.0" encoding="ISO-8859-1"?>。请帮助...

+0

[复制](http://stackoverflow.com/questions/869650/getting-simplexmlelement-to-include-the-encoding-in-output) – 2011-05-31 07:07:20

+0

为[DOM文档:: __构建体的例子](http://de3.php.net/manual/en/domdocument.construct.php)显示了如何做到这一点。在提出明显的答案之前,请参阅手册。 – Gordon 2011-05-31 07:16:45

+0

大声笑。有人注入更多的爱... – tofutim 2011-05-31 07:19:36

回答

4

http://php.net/manual/en/domdocument.savexml.php

底部。当你保存整个文件: 上一层> saveXML()在属性定义 上一层>编码编码产生串 。

当只保存一个节点时: DOMDocument-> saveXML(DOMNode)在UTF-8中总是产生 字符串。

您可以设置它在构造函数中

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

例如,

$domdoc = new DOMDocument('1.0', 'iso-8859-1'); 
+0

你的意思是说,每当我将保存整个文件,我必须检查DOMDocument->编码? – 2011-05-31 07:09:55

+0

只需用你想要的编码创建domdoc即可。 – tofutim 2011-05-31 07:16:09

1

尝试用new DomDocument('1.0', 'UTF-8');