33

Say I have a string in php, that prints out to a text file like this:

nÖ§9q1Fª£

How do I get the byte codes of this to my text file rather than the funky ascii characters?

lynn
  • 2,868
  • 5
  • 31
  • 34

4 Answers4

34

Use the ord function

http://ca.php.net/ord

eg.

<?php
$var = "nÖ§9q1Fª£ˆæÓ§Œ_»—Ló]j";

for($i = 0; $i < strlen($var); $i++)
{
   echo ord($var[$i])."<br/>";
}
?>
Gautam
  • 2,065
  • 1
  • 24
  • 24
  • 1
    @YzmirRamirez: to show bytes you need byte length, not character length, so using `mb_strlen` is actually bug. – Ped7g Oct 07 '16 at 10:50
  • You are correct @Ped7g. I generally use the mb_ functions and saw strlen call above. But the better answer is below that doesn't require for loops. – Yzmir Ramirez Oct 10 '16 at 22:08
24

If You wish to get the string as an array of integer codes, there's a nice one-liner:

unpack('C*', $string)

Beware, the resulting array is indexed from 1, not from 0!

Roman Hocke
  • 4,137
  • 1
  • 20
  • 34
6

If you are talking about the hex value, this should do for you:

$value = unpack('H*', "Stack");
echo $value[1];

Reference

Community
  • 1
  • 1
Adee
  • 464
  • 6
  • 17
2

Ord() does the trick with an ASCII-charset. If you, however, meddle with multibyte strings (like UTF-8), you're out of luck, and need to hack it yourself.

Henrik Paul
  • 66,919
  • 31
  • 85
  • 96