1

Well the title sums it up. If I do this:

fwrite($handle, 'test\r\ntest');

I get litreally that written to a file. That is:

test\r\ntest

It doesn't work for echo or any other function manipulates strings.

This became a problem when I needed to write to a printer in the serial port using ESC/POS. If I use PHP, it prints a bunch of question makrs and french characteres. With Python (plus pyserial), using the following code, works amazingly:

from __future__ import print_function
import serial

ser = serial.Serial('COM4');

ser.write('\x1b\x40');
ser.write('\x0a');
ser.write('\x0a');
ser.write('Hello there');
ser.write('\x0a');
ser.write('\x1d\x56\x42\x03');

My system: WAMP 2.4 (PHP 5.4.16, Apache 2.4.4) on Windows 7 Home Basic x64

0

3 Answers 3

5

For the backslash sign to escape special characters you need to use double-quoted strings, not single-quoted ones, try these :

fwrite($handle, 'test\r\ntest'); // not working
fwrite($handle, "test\r\ntest"); // works as expected

It may be worth noting that the problem could have been skipped altogether if your data came from another source (non-php file, web form), and happens only when you hardcode your strings inside your script file. For further details, feel free to browse the relevant manual page :

http://www.php.net/manual/en/language.types.string.php

Sign up to request clarification or add additional context in comments.

Comments

4

Using a single quote will literally write your string. To use escaped characters you need to use a double quote instead :

echo "This output will \n expand"; 

http://www.php.net/manual/en/language.types.string.php

1 Comment

I realized that the quotes were wrong, thank you. That means the problem is not there, since it still doesn't write correctly to serial port (unlike python).
2

Try using " instead of ' for these escape sequences:

fwrite($handle, "test\r\ntest");

Comments

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.