如何通过php SimpleXMLElement使用UTF-8保存xml文件

时间:2017-01-01 00:56:23

标签: php xml utf-8 simplexml

我想用php SimpleXMLElement创建sitemap.xml文件。但是当我的链接包含波斯语(波斯语)时,我有一个问题。输出文件更改单词到问号(????)。

如何通过SimpleXMLElement使用utf-8保存xml文件?

我的示例代码是:

 $a='<?xml version="1.0" encoding="UTF-8" ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

    <url>
       <loc>www.example.com/page-test/صفحه-تست/</loc>
       <changefreq>daily</changefreq>
       <priority>0.95</priority>
    </url>
</urlset>';
    $xml= new SimpleXMLElement($a);
    $xml->asXML("sitemap.xml");
像这样的出局:

<loc>www.example.com/page-test/?????-?????/</loc>

1 个答案:

答案 0 :(得分:-2)

我认为你在这里使用urlencode()htmlentities()是正确的方法,编码整个路径,而不仅仅是特殊的字符。

Demo here

www.example.com%2Fpage-test%2F%D8%B5%D9%81%D8%AD%D9%87-%D8%AA%D8%B3%D8%AA%2F