如何使用php获取Server Sent Events的直播数据?

How to get live streaming data of Server Sent Events using php?

您好,我正在使用 php 尝试服务器发送的事件 (SSE),我有一个 https url,我可以从中获取实时流数据。下面是我在无限循环中尝试的脚本。

PHP:

    <?php             
        while(1)
        {  
            $get_stream_data = fopen('https://api.xyz.com:8100/update-stream/connect', 'r');

            if($get_stream_data)
            {  
                $stream_data      =  stream_get_contents($get_stream_data);            
                $save_stream_data =  getStreamingData($stream_data);

                if($save_stream_data == true)
                {               
                    continue;                
                }            
            } 
          else
            {              
                sleep(1);
                continue;            
            }
        }    

        function getStreamingData($stream_data)
        {     

            $to       = "accd@xyz.com";
            $subject  = "Stream Details"; 
            $msg      = "Stream Details : ".$stream_data; 
            $headers  = "From:streamdetail@xyz.com";        
            $mailsent = mail($to,$subject,$msg,$headers); 

            if($mailsent){
                 return true;
            }else {
                return false;
            } 
        }
    ?>

Error:

Warning: fopen(https://api.xyz.com:8100/update-stream/connect): failed to open stream: Connection timed out in /home/public_html/get_stream_data/index.php on line 4   

服务器实时更新时我无法获取数据。

我使用以下命令在命令提示符下检查了直播。

CURL

  curl --get 'https://api.xyz.com:8100/update-stream/connect' --verbose

首先,这最好使用 PHP 的 curl 函数来完成。查看 PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

的各种答案

如果您坚持使用 fopen(),您可能需要为 SSL 设置上下文,这可能涉及安装一些证书。请参阅 file_get_contents(): SSL operation failed with code 1. And more(并注意有关已接受答案的安全警告)

最后,您的 while(1) 循环围绕着 fopen()(在相对罕见的失败后对于 re-starts 是可以的),但您实际上想要它在里面。这是您的代码,仅进行了最小的更改以表明:

<?php
    while(1)
    {  
        $get_stream_data = fopen('https://api.xyz.com:8100/update-stream/connect', 'r');

        if($get_stream_data)while(1)
        {  
            $stream_data      =  stream_get_contents($get_stream_data);            
            $save_stream_data =  getStreamingData($stream_data);

            if($save_stream_data == true)
            {               
                continue;                
            }
            sleep(1);
        } 
      else
        {              
            sleep(1);
            continue;            
        }
    }  

更新: 上面的代码仍然困扰着我:我想你想让我使用 fread() 而不是 stream_get_contents(),并使用阻塞而不是sleep(1) (在内部循环中)。 顺便说一句,我建议将 outer-loop sleep(1) 更改为 sleep(3) 或 sleep(5),这是 Chrome/Firefox/etc 中的典型默认值。 (真的,你应该寻找发送 "retry" header 的 SSE 服务器,并使用该数字作为睡眠。)