Tuesday, April 16, 2013

Print ASCII in PHP

Printing ASCII characters in PHP is easy. However various browsers would render the characters differently on the screen. Check the code below.

<?php
for($i=0;$i<=255;$i++)
{
  $b = chr($i);
  echo "<br>($i) :: [$b]";
}
?>


The above code would generate the output as shown in the picture at right::


...

Here is the output I noticed on various browsers.

Opera 12.15  :: Showed all characters
IE 8 :: Showed characters ranging 0-127, 128 onwards showed character '�' instead.
Safari 5.1.7 :: Did not show characters ranging 0-31 only [9,10,13 excluded]
Firefox 19 :: Did not show characters ranging 0-31 [9,10,13 excluded], and 128 onwards showed a question mark instead. UTF-8 encoding was enabled though.
Chrome 26.0.1410.64 m :: Did not show characters ranging 0-31 [9,10,13 excluded]

I changed the Line 4 as shown below ...

echo "<br>($i) :: [$b] [&#$i;]";

Check the output below :: [As shown in Firefox, Firefox now can show characters 128 onwards]

(123) :: [{] [{]
(124) :: [|] [|]
(125) :: [}] [}]
(126) :: [~] [~]
(127) :: [] []
(128) :: [€] [�]
(129) :: [] [�]
(130) :: [‚] [�]
(131) :: [ƒ] [�]
(132) :: [„] [�]
(133) :: […] [�]
(134) :: [†] [�]
(135) :: [‡] [�]
(136) :: [ˆ] [�]

Note : If the number is higher than 255, it would give the number % 256. Which means the statement :

echo chr(256);

would render zero ... 256 % 256 = 0

HTML characters related stuffs available at Bob Baumel's Page

No comments: