How to remove multiple UTF-8 BOM sequences

后端 未结 11 1693
故里飘歌
故里飘歌 2020-11-22 10:28

Using PHP5 (cgi) to output template files from the filesystem and having issues spitting out raw HTML.

private function fetch($name) {
    $path = $this->         


        
相关标签:
11条回答
  • 2020-11-22 11:08

    try:

    // -------- read the file-content ----
    $str = file_get_contents($source_file); 
    
    // -------- remove the utf-8 BOM ----
    $str = str_replace("\xEF\xBB\xBF",'',$str); 
    
    // -------- get the Object from JSON ---- 
    $obj = json_decode($str); 
    

    :)

    0 讨论(0)
  • 2020-11-22 11:14

    When working with faulty software it happens that the BOM part gets multiplied with every saving.

    So I am using this to get rid of it.

    function remove_utf8_bom($text) {
        $bom = pack('H*','EFBBBF');
        while (preg_match("/^$bom/", $text)) {
            $text = preg_replace("/^$bom/", '', $text);
        }
        return $text;
    }
    
    0 讨论(0)
  • 2020-11-22 11:19

    Another way to remove the BOM which is Unicode code point U+FEFF

    $str = preg_replace('/\x{FEFF}/u', '', $file);
    
    0 讨论(0)
  • 2020-11-22 11:21

    if anybody using csv import then below code useful

    $header = fgetcsv($handle);
    foreach($header as $key=> $val) {
         $bom = pack('H*','EFBBBF');
         $val = preg_replace("/^$bom/", '', $val);
         $header[$key] = $val;
    }
    
    0 讨论(0)
  • 2020-11-22 11:22

    you would use the following code to remove utf8 bom

    //Remove UTF8 Bom
    
    function remove_utf8_bom($text)
    {
        $bom = pack('H*','EFBBBF');
        $text = preg_replace("/^$bom/", '', $text);
        return $text;
    }
    
    0 讨论(0)
  • 2020-11-22 11:22

    An extra method to do the same job:

    function remove_utf8_bom_head($text) {
        if(substr(bin2hex($text), 0, 6) === 'efbbbf') {
            $text = substr($text, 3);
        }
        return $text;
    }
    

    The other methods I found cannot work in my case.

    Hope it helps in some special case.

    0 讨论(0)
提交回复
热议问题