title: PHP: convert characters to their (decimal) numeric representation (in a string)
body: <p>we are working on a project, where we have to imitate some export output of an old legacy system.</p>
  
  <p>These exports are text based and encoded in the WINDOWS-1252 encoding, where special characters should be encoded in their decimal/numeric representation, e.g. <code>α</code> should be <code>&amp;#945;</code>.</p>
  
  <p>I tried to use <code>htmlspecialchars</code>, <code>htmlentities</code> and <code>mb_convert_encoding</code> - unfortunately with no luck. </p>
  
  <p>Currently I'm iterating over each character of a string and check if it's an ASCII character or not. If the character is not valid ASCII, I'm transforming it to it's decimal representation using <code>mb_ord</code>, see my function:</p>
  
  <pre><code>private function transformString(string $str)
      {
          if (mb_check_encoding($str, 'ASCII') === true) {
              return $str;
          } else {
              $characters = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
              $transformedString = '';
              foreach ($characters as $character) {
                  if (mb_check_encoding($character, 'ASCII') === false) {
                      $character = sprintf('&amp;#%s;', mb_ord($character));
                  }
                  $transformedString .= $character;
              }
              return $transformedString;
          }
      }
  </code></pre>
  
  <p>This solution seems to work, but I'm curious if there is a cleaner way for this transformation? </p>
  
  <p>Thanks in advance!</p>