2013-10-05 29 views
6

當我使用ASP Classic腳本生成XML文件並將XML文件導入PHP頁面時,導入過程正常。PHP iconv錯誤

但是,當我通過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文件時,它工作正常。

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

+0

使用ASP Classic腳本以unicode格式製作XML。 XML使用PHP腳本編寫「UTF-8」或「ANSI」。 –

回答

0

當你這樣做會發生什麼?

如果在您確定的位置過程失敗,那麼它將無法從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內容可接受的字符集。你爲什麼想要轉換它?

4

資源:PHP official site- SimpleXMLElement documentation

如果您聲稱有在這一行錯誤:

$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(); 

?>