javascriptphputf-8echochr

echo char(128) and above from php does not work


I have a server side process.php script that echos two chars:

echo chr(127);
echo chr(128);

On the client side, I have a java script (running in an html page with UTF-8 encoding) that posts to the php script and expects a response:

const xhr = new XMLHttpRequest();
// post xhr to php, check for DONE and 200, and get the response
console.log(xhr.responseText);       

For 127, I get the response as a string with one character representing 127 as expected. But for 128 and above it gives me 3 chars, -17, -65 -67. Combed and trawled the net, but nothing. Am quite surprised to not find any info online on transmitting bytes from a server to a client. Am a desktop C++ programmer, btw hence this has me stumped!


Solution

  • Because you are sending bytes, you need to stop thinking about text and characters. JavaScript is UTF-16 internally, and you'll be transporting text across HTTP from PHP which gets to set it's own encoding.

    If you want to parse raw bytes in JavaScript, you'll want to look into the ArrayBuffer. Once you receive your data, you can compose a DataView over it and grab the bytes. If you are 8-bit only, you shouldn't need to worry about endianness, either.

            const xhr = new XMLHttpRequest();
            xhr
                .addEventListener(
                    'load',
                    () => {
                        const buffer = xhr.response;
                        const view = new DataView( buffer );
                        const byte = view.getUint8( 0 );
                        console.dir( byte );
                    }
                );
            xhr.open( 'GET', '/my/end-point' );
            xhr.responseType = 'arraybuffer';
            xhr.send();