【问题标题】:Transform 'binary' string to 'regular' string in php to save in mongodb将 'binary' 字符串转换为 php 中的 'regular' 字符串以保存在 mongodb
【发布时间】:2019-06-12 06:57:50
【问题描述】:

我在 php 中导入一个大文件,使用 PHP 7.2.10,但是有些字符串带有“b”(二进制)前缀,例如:

$str = b"PRAÇA";

当该字符串保存在 mongodb 中时,它会引发异常:

检测到字段路径“$set.field”的无效 UTF-8:PRA�A

如果我运行 mb_detect_encoding($str),它会返回“UTF-8”。

如果我运行 iconv(mb_detect_encoding($str), "UTF-8//IGNORE", $str),它会返回 "PRAA"。是的,我知道 "//IGNORE" 会忽略非 utf8 字符。

如何才能返回字符串 PRAÇA?

我真的需要成为那个字符串。

谢谢。

【问题讨论】:

标签: php mongodb php-7 php-7.2


【解决方案1】:

你可以使用这样的东西:

function binaryToString($binary)
{
    $binaries = explode(' ', $binary);
 
    $string = null;
    foreach ($binaries as $binary) {
        $string .= pack('H*', dechex(bindec($binary)));
    }
 
    return $string;    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2011-06-09
    • 2011-12-11
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多