【问题标题】:Saving XML file with UTF-8 encoding使用 UTF-8 编码保存 XML 文件
【发布时间】:2014-12-27 16:18:25
【问题描述】:

我想使用UTF-8 编码将数据存储到 XML 文件中,但它似乎不起作用.. 这是我到目前为止所做的......

public function createXML($file = 'store.xml', $products){
    if(strpos($file, "xml") === FALSE){
        $file .= ".xml";
    }
    $doc = new DOMDocument('1.0', 'utf-8'); 
    $doc->formatOutput = true; 
    $r = $doc->createElement( "Products" ); 
    $doc->appendChild( $r ); 

    foreach( $products as $product ) 
    {
        $b = $doc->createElement( "Product" ); 
        foreach($product as $key => $value){ 
            if($value !== "Picture"){
                $node = $doc->createElement($key); 
                $node->appendChild($doc->createTextNode((utf8_encode(trim($value))))); 
                $b->appendChild( $node );
            }else{
                $pictures = $doc->createElement("Picuters");
                foreach($value as $pic){
                    $node = $doc->createElement("Picture"); 
                    $node->appendChild($doc->createTextNode((utf8_encode(trim($pic)))));
                    $pictures->appendChild($node);
                }
                $b->appendChild($pictures);
            }
        }
        $r->appendChild( $b );

    } 
    $doc->save($file);
}

但它并没有像我想要的那样保存数据..

文件中的数据是这样的..

<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <Brand>Milla by trendyol</Brand>
    <ProductCode>Bluz</ProductCode>
    <ProductName>Güpür Detaylı Bordo</ProductName>
    <ProductURL>http://www.trendyol.com/Gupur-Detayli-Bordo-Bluz/UrunDetay/29920/8562520</ProductURL>
    <ProductStatus>Yes</ProductStatus>
    <Category>Bluz</Category>
    <Gender>Kadın</Gender>
    <OldPrice>69.99</OldPrice>
    <Unit>TL</Unit>
    <NewPrice>49.99</NewPrice>
    <Picture>http://www.trendyol.com/http://s.trendyol.com/Assets/ProductImages/29043/T00400SV6A001_1_org.jpg</Picture>
    <Tags>Güpür Detaylı Bordo, Güpür, Detaylı, Bordo, Butik,Kadin,Luks &amp; Tasarim,Ayakkabi &amp; canta,Milla by trendyol,Women</Tags>
    <EndDate>29.12.2014 22:00:00</EndDate>
  </Product>
</Products>

喜欢性别

<Gender>Kadın</Gender>

应该是这样的

<Gender>Kadïn</Gender>

还有其他类似的东西。

请帮忙....

谢谢。

【问题讨论】:

  • 如何读取 XML 文件?也许您用来读取它的程序无法识别 UTF-8 编码,并将文件视为被编码为 ISO-8859-1 或其他 1 字节字符集。
  • 我尝试使用编码UTF-8重新打开,但还是一样

标签: php xml encoding utf-8


【解决方案1】:

确保您的输入数据尚未编码为UTF-8,因为如果是,您将通过调用utf8_encode() 对其进行双重编码。如果您希望遇到编码为UTF-8 的字符串并且还使用其他字符集(我猜是ISO-8859-9),那么我认为最好用这样的函数替换utf8_encode()

function encode_to_utf8_if_needed($string)
{
    $encoding = mb_detect_encoding($string, 'UTF-8, ISO-8859-9, ISO-8859-1');
    if ($encoding != 'UTF-8') {
        $string = mb_convert_encoding($string, 'UTF-8', $encoding);
    }
    return $string;
}

正如documentation 所说,函数utf8_encode() 将ISO-8859-1 字符串编码为UTF-8。对于已经编码为 UTF-8 的字符串或使用不同的字符集,它不会产生所需的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 2016-08-14
    • 2015-07-31
    • 2011-02-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多