Home > Article > Backend Development > How to solve php socket garbled problem
Solution to php socket garbled code: First check the encoding of the error message through the "mb_detect_encoding(socket_last_error($socket))" method; then convert the error message to "UTF-8" encoding.
PHP writing socket error message garbled problem
Problem
Because the default of PHP project is The UTF-8 encoding is used. Since the error message when using socket programming is not the UTF-8 encoding used, the output errors are displayed in garbled characters on the browser and console.
The error message is as follows:
socket_connect(): unable to connect [10061]: ����Ŀ����������ܾ��������ӡ�
Processing process
1. First, check the encoding of the error message through the following code
mb_detect_encoding(socket_last_error($socket))
The result is output as ASCII .
2. From the check results in the first step, we know that the encoding of the error message is not UTF-8, so the error message needs to be converted to UTF-8 encoding. This can be achieved through the following function:
function doEncoding($str){ $encode = strtoupper(mb_detect_encoding($str, ["ASCII",'UTF-8',"GB2312","GBK",'BIG5'])); if($encode!='UTF-8'){ $str = mb_convert_encoding($str, 'UTF-8', $encode); } return $str; }
After this code conversion, the output result is normal
socket_connect() failed. Reason: The connection cannot be made because the target computer actively refuses.
For more related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to solve php socket garbled problem. For more information, please follow other related articles on the PHP Chinese website!