[英]PHP iconv error
當我使用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文件時,它可以正常工作。
資源: 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();
?>
當你這樣做時會發生什么:
$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內容的可接受字符集。 你為什么要轉換它?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.