phpphpwebsocketbinance-api-client

Listen WebSocket with php


I want to get instant cryptocurrency prices on Binance with the help of Websocket. I can do this with javascript as follows. However, this is not useful for me as javascript works on the client side. I want to do this with php to run on the server. I found a few examples in my research, but they were not the solution for me.

Below is a javascript example and I want to learn how to do it in php.

var socket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@ticker");

socket.onmessage = function (event) {
    var data = JSON.parse(event.data);
    console.log(data);
}

Solution

  • I have two classes you can use to connect to the websocket server from php

    The sources are at https://github.com/napengam/phpWebSocketServer/tree/master/phpClient

    <?php
    
    include __DIR__ . "/../phpClient/websocketCore.php";
    
    class websocketPie extends websocketCore {
    
        public $uuid, $connected = false, $chunkSize = 6 * 1024;
    
        //private $socketMaster;
    
        function __construct($Address, $Port = '', $app = '/', $uu = '') {
    
            if (parent::__construct($Address, $Port, $app, $uu) == false) {
                return;
            }
           
            $respo = $this->readSocket();
            echo var_dump(json_decode($respo));
        }
    
    }
    
    $x = new websocketPie("wss://stream.binance.com","9443","/ws/btcusdt@ticker");
    

    The output of above script below:

    F:\xampp-htdocs\phpWebSocketServer\websocketExtern\websocketPie_1.php:18:
    object(stdClass)[2]
      public 'e' => string '24hrTicker' (length=10)
      public 'E' => int 1626263895576
      public 's' => string 'BTCUSDT' (length=7)
      public 'p' => string '-623.48000000' (length=13)
      public 'P' => string '-1.885' (length=6)
      public 'w' => string '32342.75143871' (length=14)
      public 'x' => string '33074.69000000' (length=14)
      public 'c' => string '32451.21000000' (length=14)
      public 'Q' => string '0.00356600' (length=10)
      public 'b' => string '32451.21000000' (length=14)
      public 'B' => string '0.00534800' (length=10)
      public 'a' => string '32451.22000000' (length=14)
      public 'A' => string '0.40745100' (length=10)
      public 'o' => string '33074.69000000' (length=14)
      public 'h' => string '33078.98000000' (length=14)
      public 'l' => string '31550.00000000' (length=14)
      public 'v' => string '51376.85373100' (length=14)
      public 'q' => string '1661668809.92454695' (length=19)
      public 'O' => int 1626177495575
      public 'C' => int 1626263895575
      public 'F' => int 954365122
      public 'L' => int 955537825
      public 'n' => int 1172704