如何从套接字打印最后一个字符串


How to print the last string from socket

我试图从服务器响应打印最后一个字符串。我写了以下内容:

$fp = fsockopen("smtp.mail.ru", 25);
// There is fputs functions
echo fgets($fp);// This is print the first string

但是我想打印服务器响应的最后一个字符串。有可能做到吗?

您可以将字符串放入字符串数组中,然后打印最后一个字符串:

<?php
$cntr = 0;
$strarray = [];
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) 
{
    echo "$errstr ($errno)<br />'n";
} 
else 
{
    $out = "GET / HTTP/1.1'r'n";
    $out .= "Host: www.example.com'r'n";
    $out .= "Connection: Close'r'n'r'n";
    fwrite($fp, $out);
    while (!feof($fp)) 
    {
        $strarray[$cntr] = fgets($fp);
        $cntr = $cntr + 1;
    }
    fclose($fp);
}
//Now, print the last string in the array:
echo end($strarray);
?>