【问题标题】:How fix UTF-8 Characters in PHP file_get_contents()如何修复 PHP file_get_contents() 中的 UTF-8 字符
【发布时间】:2016-02-28 07:28:17
【问题描述】:

当我使用file_get_contents($url) 时,当我回显它时,它会返回一个外来字符。

但它只能在某些网站上看到,在其他网站上可以正常工作:

我的代码是:

<?php
header ( "Content-Type: text/html;charset=utf-8" );
$url ="http://www.varzesh3.com/news/1307290";
echo $go_to = file_get_contents($url);
?>

【问题讨论】:

  • 确保您正在读取的文件和读取它的 PHP 脚本都是 UTF-8 编码的(没有 BOM 的 UTF-8)。
  • 对不起,我没听懂。
  • 如果您正在阅读的文件已经是 utf-8 编码的,您根本不需要转换任何内容。但是 php 脚本也必须是 utf-8 编码的。否则它不能正确处理文件内容。您可以通过几个编辑器更改脚本文件的编码。其中之一是 Notepad++。
  • Plus:mb_convert_encoding 等函数将转换字符转换为 utf-8。如果原始文件不包含 utf-8 字符,则脚本无法创建它们。

标签: php utf-8 file-get-contents


【解决方案1】:

根据PHP手册:

如果您对 file_get_contents 有疑问,可以使用此代码!

<?php
function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
?>

【讨论】:

  • 嗯,现在试试这个:$result = mb_convert_encoding($last_file, 'HTML-ENTITIES', "UTF-8");
  • 天哪,对不起我的朋友,但事实并非如此。对于示例 url 测试此链接:varzesh3.com/news/1307397
  • 我想接收 "varzesh3.com/news/1307397" html 代码。但是当我使用 [file_get_contents] 并回显此无法查看时。此站点未显示允许的代码..
  • 请尝试$content = @file_get_contents($fn);,如果不行,我们再做决定
  • no no no 抱歉,请自行测试。 echo file_get_contents(varzesh3.com/news/1307397/%22);
【解决方案2】:

并设置标题,它需要首先将 php 发送到客户端浏览器

header('Content-Type: text/html; charset =utf-8');

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2012-07-11
    • 2011-01-12
    相关资源
    最近更新 更多