【问题标题】:PHP - html_entity_decode not decoding everythingPHP - html_entity_decode 不解码一切
【发布时间】:2014-01-23 05:34:42
【问题描述】:

我正在解析一个 HTML 页面。在某些时候,我正在获取 div 和使用之间的文本 html_entity_decode 打印该文本。

问题是页面包含像这​​个星这样的字符或其他像⬛︎、◄、◉等形状的字符。我检查了这些字符并没有在源页面上编码,它们就像你看到的一样正常。

页面正在使用 charset="UTF-8"

所以,当我使用

html_entity_decode($string, ENT_QUOTES, 'UTF-8');

例如,星号被“解码”为â˜

$string 正在使用

获取
document.getElementById("id-of-div").innerText

我想正确解码它们。我如何在 PHP 中做到这一点?

注意:我已经尝试过htmlspecialchars_decode($string, ENT_QUOTES);,它产生了相同的结果。

【问题讨论】:

  • 1.星星是否有等效的 HTML 实体? 2. 那么,$string 包含什么? 3. 对我来说似乎是字符代码问题。
  • 1.我没有头绪。 2.理论上所有的字符串都包含在一个特定的div中。 3. 我不确定。
  • "我已经检查,这些字符没有在源页面上编码......我想正确解码它们。"如果它们没有被编码,你希望如何解码它们? html_entity_decode 纯粹是将&something; 形式的实体(包括something 的数值)转换为“真实”字符。您在此处拥有的内容看起来像一个 UTF-8 字符串,然后您将在非 UTF-8 上下文中回显它。
  • 确实如此。部分问题实际上是,为什么你要这样做?如果您有一些 UTF-8 字符要打印出来,那您为什么要进行 html_entity_decode 呢?为什么不只是,呃,打印出来?我们可以看看源文档和您的实际代码的示例吗?
  • 我刚刚对您问题中的字符进行了 html_entity_decode 测试,并且正如预期的那样,它使它们保持不变。你是如何创建你的输出的,你是如何看待它的?我的猜测:html_entity_decode 是一个红鲱鱼,你实际上是在输出未触及的 UTF-8 字符,但是你的字符编码是错误的,所以它们在显示时被破坏了。

标签: php html parsing dom


【解决方案1】:

我试图用这个简单的 PHP 来重现你的问题:

<?php
  // Make sure our client knows we're sending UTF-8
  header('Content-Type: text/plain; charset=utf-8');
  $string = "The page contains characters like this star ★ or others like shapes like ⬛︎, ◄, ◉, etc. Here are some entities: This is a &quot;test&quot;.";
  echo 'String: ' . $string . "\n";
  echo 'Decoded: ' . html_entity_decode($string, ENT_QUOTES, 'UTF-8');

正如预期的那样,输出是:

String: The page contains characters like this star ★ or others like shapes like ⬛︎, ◄, ◉, etc. Here are some entities: This is a &quot;test&quot;.
Decoded: The page contains characters like this star ★ or others like shapes like ⬛︎, ◄, ◉, etc. Here are some entities: This is a "test".

如果我将标题中的字符集更改为iso-8859-1,我会看到:

String: The page contains characters like this star ★ or others like shapes like ⬛︎, ◄, ◉, etc. Here are some entities: <span>This is a &quot;test&quot;.
Decoded: The page contains characters like this star ★ or others like shapes like ⬛︎, ◄, ◉, etc. Here are some entities: <span>This is a "test".

所以,我会说您的问题是显示问题。正如您所料,html_entity_decode 完全没有触及“有趣”的角色。只是你得到的任何代码,或者你用来查看输出的任何代码,都错误地使用了 iso-8859-1 来显示它们。

【讨论】:

  • 你是对的!谢谢!我忘了在代码的开头添加header('Content-Type: text/html; charset=utf-8');,所以它会强制 UTF-8 输出。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多