Question

I want to create a string of non-standard characters in PHP, such as characters 128-255, and then encode said string as CP1252:

<?php
$cp1252 = '';

for ($i = 128; $i < 256; $i++) {
    $hex = dechex($i);
    $cp1252 .= "\x$hex";
}

echo $cp1252;

I knew this wouldn't work because the escape sequence is parsed before the variable is initialized (correct me if I'm wrong), so this serves as an example of what I'd like to do.

This is the final code I used to test the conversion of CP1252 to UTF-8:

<?php
$cp1252 = '';

for ($i = 128; $i < 256; $i++) {
    $cp1252 .= chr($i);
}

echo iconv("CP1252", "UTF-8", $cp1252);
Was it helpful?

Solution

Use the chr() function to convert a character code to a string:

for ($i = 128; $i < 256; $i++) {
    $cp1252 .= chr($i);
}

OTHER TIPS

To generate a string of random characters:

function rand_cp1252($length) {
  $ostr = '';
  for($i=0;$i<$length; $i++) {
    $ostr .= chr(rand(128,255));
  }
  return $ostr;
}

echo rand_cp1252(10);

As far as the 'encoding' goes that has nothing to do with the string itself, you want to make sure you're setting the correct headers for the encoding type when you serve the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top