title: Unicode symbols become "??????????" at PHP side but data is NVARCHAR and SELECT shows correct data
body: <p>I have a database with SQL_Latin1_General_CP1_CI_AS collation that I need to convert to utf8_unicode_ci collation. Altering the table is not an option. MSSQL returns data like this:</p>
  
  <pre><code>[FirstName] =&gt; ??????????
  </code></pre>
  
  <p>but true data like this:</p>
  
  <pre><code>[FirstName] =&gt; مریم
  </code></pre>
  
  <p>I have tried these ways:</p>
  
  <pre><code>$utf8[] = utf8_encode($saleagent['FirstName']);
  $utf8[] = iconv('ISO-8859-1', 'UTF-8',$saleagent['FirstName']);
  $utf8[] = mb_convert_encoding($saleagent['FirstName'], 'UTF-8', 'ISO-8859-1');
  </code></pre>
  
  <p>the output is :</p>
  
  <pre><code>Array
  (
      [0] =&gt; ??????????
      [1] =&gt; ??????????
      [2] =&gt; ??????????
  )
  </code></pre>
  
  <p>Is there any way to convert the existing data to utf8_unicode_ci?</p>
  
  <p><strong>Edit</strong></p>
  
  <hr>
  
  <p>According to <a href="https://stackoverflow.com/a/10143652/9183427">this answer</a>, I changed my code:</p>
  
  <p>In SQL:</p>
  
  <pre><code>CAST(p.FirstName AS VARBINARY(MAX)) as FirstName,
  </code></pre>
  
  <p>In PHP I wrote this function to fix the encoding:</p>
  
  <pre><code>public function fixEncoding($string)
  {
      $original = $string;
      $string = trim($string);
      // Detect the input string encoding.
      $encoding = mb_detect_encoding($string, mb_detect_order(), false);
  
      if ($encoding == 'UTF-8' || $encoding == false) {
          $hex = bin2hex($string);
  
          $str = "";
          for ($i = 0; $i &lt; strlen($hex) - 1; $i += 2) {
              $str .= chr(hexdec($hex[$i] . $hex[$i + 1]));
          }
          $string = iconv('UCS-2LE', 'UTF-8', $str);
          return $string;
  
      } elseif ($encoding == 'ASCII') {
          $string = $original;
          return $string;
      }
  
      return $string;
  }
  </code></pre>
  
  <p>let me explain the situation.
  I encounter with 3 types of strings in the <code>mssql</code> database:</p>
  
  <ol>
  <li>Strings like English characters or numbers: <code>xyz 32 -</code></li>
  <li>Strings like Persian characters: <code>مریم دختر خوبی است</code></li>
  <li>Strings like both above: <code>مریم دختر خوبی است - Maryam is a good girl.</code></li>
  </ol>
  
  <p>What happens is, the in <strong>1</strong> and <strong>2</strong> the code convert it successfully. However, number <strong>3</strong> returns error while it tries to convert it with <code>iconv</code> and it throws the error below:</p>
  
  <blockquote>
    <p>iconv(): Detected an incomplete multibyte character in input string</p>
  </blockquote>
  
  <p>In this line:</p>
  
  <pre><code>$string = iconv('UCS-2LE', 'UTF-8', $str);
  </code></pre>
  
  <p>Do you have any solution to handle all 3 situations?</p>