【问题标题】:PHP HTML encodingPHP HTML 编码
【发布时间】:2013-10-12 14:07:02
【问题描述】:

我正在尝试解析 HTML 页面,但编码弄乱了我的结果。经过一番研究,我发现了一个非常流行的解决方案,使用utf8_encode()utf8_decode(),但它并没有改变任何东西。在以下几行中,您可以检查我的代码和输出。

代码

$str_html = $this->curlHelper->file_get_contents_curl($page);
$str_html = utf8_encode($str_html);

$dom = new DOMDocument();
$dom->resolveExternals = true;
$dom->substituteEntities = false;
@$dom->loadHTML($str_html);
$xpath = new DomXpath($dom);

(...)
$profile = array();
for ($index = 0; $index < $table_lines->length; $index++) {
    $desc = utf8_decode($table_lines->item($index)->firstChild->nodeValue);
}

输出

Testar é bom

应该是

Testar é bom

我尝试过的

  • htmlentities():

    htmlentities($table_lines-&gt;item($index)-&gt;lastChild-&gt;nodeValue, ENT_NOQUOTES, ini_get('ISO-8859-1'), false);

  • htmlspecialchars():

    htmlspecialchars($table_lines-&gt;item($index)-&gt;lastChild-&gt;nodeValue, ENT_NOQUOTES, 'ISO- 8859-1', false);

  • 将我的文件字符集更改为here

更多信息

  • 网站编码:&lt;meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /&gt;

提前致谢!

【问题讨论】:

标签: php html character-encoding


【解决方案1】:

在没有utf8_decode() 的情况下尝试使用以下内容:

mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');

或者,不要使用utf8_decode() 并尝试将您的网站元更改为:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

【讨论】:

  • 谢谢,成功了!只是为了理解......既然我的HTML是ISO-8859-1,为什么它被传递为$to_encodingUTF-8作为$from_encoding
  • @Doon 因为您尝试打印的字符串采用UTF-8 编码,但需要采用ISO-8859-1 编码才能正确打印在您的ISO-8859-1 编码网站上。所以很自然,你需要从UTF-8 转换为ISO-8859-1 编码。
  • 哦,我明白了。再次感谢!
猜你喜欢
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多