6

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

但是,当我通过 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 文件时,它工作正常。

4

2 回答 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();

?>
于 2013-10-20T13:04:38.627 回答
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 内容字符集。你为什么要转换它?

于 2013-10-05T15:38:17.217 回答