【问题标题】:How can I convert input to HTML Characters correctly如何正确将输入转换为 HTML 字符
【发布时间】:2010-04-03 14:44:13
【问题描述】:

假设我包含一个包含 html 的文件。 html 有字符作为感叹号,西班牙口音(á,ó)。解析后的包含文本被处理为符号而不是它们的正确值。这发生在 FF 上,但不在 IE (8) 上。

我尝试了以下功能:

htmlspecialchars、htmlentities、utf8_encode

include htmlentities("cont/file.php");

示例 file.php 内容:

<div>Canción, “Song Name”</div>

输出:

Canci�n, �Song Name�

【问题讨论】:

    标签: php html encoding character-encoding


    【解决方案1】:

    您的代码除了通过 htmlentities() 运行字符串“cont/fie.php”之外什么都不做,文件的内容不受此影响。

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      charset parameter 中输出指定您正在使用的character encoding(推荐使用UTF-8)的HTTP Content-Type 标头。

      【讨论】:

        【解决方案4】:

        echo htmlentities(file_get_contents("cont/file.php")); 可能是您要问的。
        但是,如前所述,您不能使用 htmlentities 而是使用 UTB-8 编码

        【讨论】:

        • 我只需要在包含文件中搜索特殊字符并在包含之前转换为html实体。
        • @Codex73 如果您已经使用 utf-8,并且您的文本 indeed 在 utf-8 中,则无需将字符转换为实体。扔掉htmlentities
        【解决方案5】:

        这就是你的代码和我的代码最终在两个不同的地方工作的原因;原因很难知道,但需要解析。

        这是显示的浏览器(FF + IE)-->

        alt text http://i77.photobucket.com/albums/j65/speedcoder/4-3-20101-22-31PM.png

        Sample**('include' 函数未使用,因此不需要输出缓冲区):

        <?php 
        $varr = '<div>ääääääó</div>'; 
        echo utf8_encode($varr); 
        ?>
        

        这个对我不起作用:

        <?php
           include "test.php";
        ?>
        

        如果上面的示例使用带有 html 代码的包含文件,它至少对我来说没有转换字符。我将其更改为不包含文件并使用 utf8_encode,但问题是我的代码需要使用不起作用的包含函数。

        下面的下一个示例使用 include 方法和输出缓冲区,它允许在 utf8_encode 编码发生之前渲染和解析代码。

        我的代码场景(对于我的特定场景必须使用 ob,因为包含文件还包含需要首先解析的代码):

        ob_start(); 
        include ("cont/file.php"); 
        $content = ob_get_contents(); 
        ob_end_clean(); 
        echo utf8_encode($content); 
        

        感谢您帮我解决“Ondrej Slinták”!!!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-05-15
          • 2021-11-21
          • 1970-01-01
          • 2013-08-21
          • 2013-09-23
          • 1970-01-01
          • 2015-12-03
          相关资源
          最近更新 更多