3

We've got some stupid and unrecompilable client code which sends a string to a webservice. The format of the string is created using this code in C#

        string strAscii = "";

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding ( );
        byte[] arrOrg = encoding.GetBytes ( strOrg );

        for ( int i = 0; i < arrOrg.Length; i++ )
        {
            strAscii += arrOrg[ i ].ToString ( "x2" );
        }

        return strAscii;

This has got to be unravelled by a PHP page. The only way I've managed to get this to work is by converting each couplet of the string to a byte value and putting them into an array.

And then by running this monstrosity:

$arrBytes = array( 0xc3, 0xa9); // this is a single UTF-8 character (e acute)

$fh = fopen("./temp.tmp", "w+");
for($i = 0; $i < count($arrBytes); $i++)
{
    fprintf($fh, "%c", $arrBytes[$i]);
}
fclose($fh);

$str = file_get_contents("./temp.tmp");

echo $str;

This works, but it's ridiculous.

Is there any better way of doing it? I've tried all the "standard" type ways, mb_convert_encoding, iconv and pack but to no avail.

5
  • Perhaps you should post an minimal reproducible example of the 'standard' things you tried and the results. Commented Sep 12, 2017 at 17:13
  • Possible duplicate of Array of bytes to UTF-8 string in PHP? Commented Sep 12, 2017 at 17:15
  • 4
    how about: hex2bin("6578616d706c65206865782064617461") ? Commented Sep 12, 2017 at 17:19
  • @pvg one of the standard things I tried was in the possible duplicate you cited. Unfortunately for me that didn't work and so I don't believe it is a duplicate, yet it does serve as an example of what I've tried. Commented Sep 12, 2017 at 18:08
  • @RolandStarke This worked. Brilliant, but annoying as I've spent ages trying to fix this... Commented Sep 12, 2017 at 18:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.