在PHP中编写UTF8编码的文件
我正在编写一个函数来动态生成站点地图和站点地图索引。
根据 sitemap.org 上的文档,该文件应采用 UTF-8 编码。
我编写文件的函数是一个相当简单的函数,大致如下:
function generateFile()
{
$xml = create_xml();
$fp = @fopen('sitemap', 'w');
fwrite($fp, $xml);
fclose($fp);
}
[编辑 - 在注释后添加]
create_xml() 很简单,如下所示:
function create_xml()
{
return '<?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>http://example.com/</loc>
<lastmod>2006-11-18</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
</urlset>';
}
有什么特别需要的吗如何确保文件采用 UTF-8 编码?
此外,我想对文件进行 gzip 压缩,而不是不压缩。我知道如何在将文件保存到磁盘后压缩该文件。我想知道是否(如何?)我可以在写入磁盘之前压缩文件吗?
I am writing a function to dynamically generate my sitemap and sitemap index.
According to the docs on sitemap.org, the file should be encoded in UTF-8.
My function for writing the file is a rather simplistic one, something along the lines of:
function generateFile()
{
$xml = create_xml();
$fp = @fopen('sitemap', 'w');
fwrite($fp, $xml);
fclose($fp);
}
[Edit - added after comments ]
The create_xml() is simplistic, like so:
function create_xml()
{
return '<?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>http://example.com/</loc>
<lastmod>2006-11-18</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
</urlset>';
}
Is there anything in particular I need to do to ensure that the file is encoded in UTF-8?
Additionally, I would like to gzip the file, rather than leaving it uncompressed. I know how to compress the file AFTER I have saved it to disk. I want to know if (how?), can I compress the file BEFORE writing to disk?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您需要确保您的内容(
create_xml()
的输出编码为 UTF-8。为了确保这一点,您可以使用 utf8_encode()。您需要确保 XML 文件指定'wb'
模式下fopen
,b表示二进制,这将确保数据完全按原样写入。Yes, you need to make sure your content (the output of
create_xml()
is encoded as UTF-8. To ensure this, you can use utf8_encode(). You need to make sure the XML file specifies<?xml version="1.0" encoding="UTF-8"?>
. And I'd suggest tofopen
in the'wb'
mode, the b meaning binary. This will ensure the data gets written exactly as-is.您的 PHP 脚本文件应保存为 utf-8。
另外,如果没有看到
create_xml()
的作用,就很难说更多Your PHP script files should be saved as utf-8.
Also, it's hard to say more without seeing what
create_xml()
does如果您仅使用 ASCII 字符,您的文件将始终采用 UTF-8。
If you are using only ASCII characters, your file will be always in UTF-8.