How to solve php socket garbled problem

藏色散人
Release: 2023-03-02 13:30:02
Original
3688 people have browsed it

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.

How to solve php socket garbled problem

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]: ����Ŀ����������ܾ����޷����ӡ�
Copy after login

Processing process

1. First, check the encoding of the error message through the following code

mb_detect_encoding(socket_last_error($socket))
Copy after login

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;
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template