PHP iconv 错误

6

当我使用ASP Classic脚本生成一个XML文件,并在PHP页面中导入该XML文件时,导入过程正常。

但是,当我通过PHP脚本(而不是ASP Classic)生成相同的XML并在同一个导入过程中使用它时,就无法正常工作。

$xml = iconv("UTF-16", "UTF-8", $xml);

我在导入过程中注意到以下情况:
  • 在我的代码的$xml = iconv("UTF-16", "UTF-8", $xml); 代码行之前,XML 文件格式正确。
  • 但是,在$xml = iconv("UTF-16", "UTF-8", $xml); 代码行之后,XML文件就会损坏。
如果我将此代码行注释掉并使用 PHP XML 文件,则一切正常。

使用ASP Classic脚本制作的XML采用Unicode格式。而使用PHP脚本制作的XML则可以采用"UTF-8"或"ANSI"格式。 - Deniyal Tandel
2个回答

4

资源: PHP官方网站 - SimpleXMLElement文档

如果你认为这行代码中存在错误:

$xml = iconv("UTF-16", "UTF-8", $xml);

然后将其更改为以下内容,因为 $xml 可能不是 "UTF-16" 格式:
$xml = iconv(mb_detect_encoding($xml), "UTF-8", $xml);

保存XML文件的方法如下:
//saving generated xml file
$xml_student_info->asXML('file path and name');

导入XML文件的步骤:

$url = "http://www.domain.com/users/file.xml";
$xml = simplexml_load_string(file_get_contents($url));

如果您有以下的数组:
$test_array = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);

如果你希望将其转换为以下XML格式:

<?xml version="1.0"?>
<main_node>
    <bla>blub</bla>
    <foo>bar</foo>
    <another_array>
        <stack>overflow</stack>
    </another_array>
</main_node>

下面是 PHP 代码:

<?php

//make the array
$test = array (
  'bla' => 'blub',
  'foo' => 'bar',
  'another_array' => array (
    'stack' => 'overflow',
  ),
);   

//make an XML object
$xml_test = new SimpleXMLElement("<?xml version=\"1.0\"?><main_node></main_node>");

// function call to convert array to xml
array_to_xml($test,$xml_test);

//here's the function definition (array_to_xml)
function array_to_xml($test, &$xml_test) {
    foreach($test as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_test->addChild("$key");
                array_to_xml($value, $subnode);
            }
            else{
                $subnode = $xml_test->addChild("item$key");
                array_to_xml($value, $subnode);
            }
        }
        else {
            $xml_test->addChild("$key","$value");
        }
    }
}

/we finally print it out
print $xml_test->asXML();

?>

0

当你执行以下操作时会发生什么:

$xml = iconv("UTF-16", "UTF-8//IGNORE", $xml);

?

如果进程在您已经确定的点失败,则表示它无法从UTF-16转换为UTF-8,这意味着输入字符串中有一个或多个字符没有UTF-8表示。 "//IGNORE"标志将默默丢弃这些字符,这显然是不好的,但使用该标志可以帮助确定我认为的问题是否实际存在。您还可以尝试转换失败的字符:
$xml = iconv("UTF-16", "UTF-8//TRANSLIT", $xml);

字符将被近似,因此您至少会保留一些内容。请参见此处的示例:http://www.php.net/manual/en/function.iconv.php

话虽如此,UTF-16是XML内容的可接受字符集。您为什么想要进行转换?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接