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

时间:2014-03-11 13:55:08

标签: php string sockets

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

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

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

1 个答案:

答案 0 :(得分:0)

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

<?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);

?>