如何在PHP中显示特殊字符 [英] How to display special characters in PHP

查看:422
本文介绍了如何在PHP中显示特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次看到这个问题,但是分辨率不高.我有以下字符串:

I've seen this asked several times, but not with a good resolution. I have the following string:

$string = "<p>Résumé</p>";

我想打印或回显字符串,但是输出将返回<p>R�sum�</p>.因此,我尝试使用htmlspecialchars()htmlentities()来输出&lt;p&gt;R&eacute;sum&eacute;&lt;p&gt;,浏览器将呈现&lt;p&gt;R&eacute;sum&eacute;&lt;p&gt;.显然,我希望它呈现为这样:

I want to print or echo the string, but the output will return <p>R�sum�</p>. So I try htmlspecialchars() or htmlentities() which outputs &lt;p&gt;R&eacute;sum&eacute;&lt;p&gt; and the browser renders &lt;p&gt;R&eacute;sum&eacute;&lt;p&gt;. I want it, obviously, to render this:

简历

我正在使用UTF-8:

And I'm using UTF-8:

header("Content-type: text/html; charset=UTF-8");

我在这里想念什么?为什么echoprint为任何特殊字符输出?为了澄清,该字符串实际上是存储在数据库中的整个HTML文件.现实世界中的应用程序不只是那条小线.

What am I missing here? Why do echo and print output a for any special character? To clarify, the string is actually an entire HTML file stored in a database. The real-world application is not just that one small line.

推荐答案

经过多次敲打,我对我想发布给可能遇到此问题的其他人的问题有了更好的了解

After much banging-head-on-table, I have a bit better understanding of the issue that I wanted to post for anyone else who may have had this issue.

虽然UTF-8字符集将在客户端上显示特殊字符,但另一方面,服务器可能不那么友好,而是将特殊字符(例如àè)打印为.

While the UTF-8 character set will display special characters on the client, the server, on the other hand, may not be so accomodating and would print special characters such as à and è as and .

要确保您的服务器可以正确打印它们,请使用ISO-8859-1字符集:

To make sure your server will print them correctly, use the ISO-8859-1 charset:

<?php
    /*Just for your server-side code*/
    header('Content-Type: text/html; charset=ISO-8859-1');
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"><!-- Your HTML file can still use UTF-8-->
        <title>Untitled Document</title>
    </head>
    <body>
        <?= "àè" ?>
    </body>
</html>

这将正确打印:àè

我现在有了更好的理解.起作用的原因是通过响应header()告知客户端(浏览器)期望ISO-8859-1文本/html文件. (正如其他人所提到的,您也可以通过更新.ini.htaccess文件来做到这一点.)然后,一旦浏览器开始将给定文件解析为DOM,输出将服从任何<meta charset="">规则,但保持ISO字符完整.

I have a little better understanding now. The reason this works is that the client (browser) is being told, through the response header(), to expect an ISO-8859-1 text/html file. (As others have mentioned, you can also do this by updating your .ini or .htaccess files.) Then, once the browser begins to parse that given file into the DOM, the output will obey any <meta charset=""> rule but keep your ISO characters intact.

这篇关于如何在PHP中显示特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆