【问题标题】:PHP and UTF-8 string compairsPHP 和 UTF-8 字符串比较
【发布时间】:2013-08-03 06:11:19
【问题描述】:

我经常使用这段代码和类似的东西来解析文件...

if ($dataLines[0] == "0 HEAD" && 
    ($dataLines[count($dataLines) - 1] == "0 TRLR" ||
     $dataLines[count($dataLines) - 2] == "0 TRLR")) {
              // More Code Here
}

我添加了以下 else 用于调试...

} else {
    $this->error("import(): File is not a gedcom datafile: " . $filename);
    $this->debug("import(): Lines: " . count($dataLines));
    $this->debug("import(): Lines: dataLines[0] = [" . $dataLines[0] ."]");
    $this->debug("import(): Lines: dataLines[count($dataLines) - 1] = [" . $dataLines[count($dataLines) - 1] ."]");
}

当我解析 ANSII 文件时,一切正常。我收到了一个 UTF-8 格式的文件,然后事情就坏了。我的输出是:

Starting gedcom read
import(): File is not a gedcom datafile: /Users/jzaun/Development/www/assets/trees/greek/tree.ged
import(): Lines: 10712
import(): Lines: dataLines[0] = [0 HEAD ]

我也遇到了错误:

PHP 致命错误:在 /Users/jzaun/Development/www/classes/App/Gedcom.php:478 中未捕获的异常“ErrorException”和消息“数组到字符串转换” 堆栈跟踪:

要加载我正在使用的文件:

function file_get_contents_utf8($fn) {
    $content = file_get_contents($fn);
    return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content));
}

$data = $this->file_get_contents_utf8($filename);
$dataLines = explode("\n", trim($data));
if (count($dataLines) == 1) {
    $dataLines = explode("\r", trim($data));
}

我猜我要么加载文件错误,要么我不应该做像$dataLines[0] == "0 HEAD" 这样的事情。我应该如何解析文件以使其适用于 UTF-8?

【问题讨论】:

    标签: php parsing utf-8


    【解决方案1】:

    这个

    
    

    是Byte Order Mark (BOM)。这可能是您的问题,因为它正在更改第一行并且您的比较失败。

    如果前三个字节等于,则必须忽略/删除它们。一个例子请参见this answer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-17
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2017-10-28
      • 1970-01-01
      • 2016-05-31
      相关资源
      最近更新 更多