因为从'Action:Status'命令返回的数据量可以是任何大小...我担心在第13行使用带有fread()的静态数字。我也尝试过使用fgets()但是它只抓取第一行数据(META HTTP行......没有表)。如何使用PHP从套接字中获取任意数量的数据?请帮忙
<?php
$ami = fsockopen("192.100.100.180", 5038, $errno, $errstr);
if (!$ami) {
echo "ERROR: $errno - $errstr<br />\n";
} else {
fwrite($ami, "Action: Login\r\nUsername: 1005\r\nSecret: password\r\nEvents: off\r\n\r\n");
fwrite($ami, "Action: Status\r\n\r\n");
sleep(1);
$record = fread($ami,9999);#this line could over run!!!
$record = explode("\r\n", $record);
echo "<META HTTP-EQUIV=Refresh CONTENT=\"9\">"; #refresh page every 9 seconds
echo "<table border=\"1\">";
foreach($record as $value){
if(!strlen(stristr($value,'Asterisk'))>0
&& !strlen(stristr($value,'Response'))>0
&& !strlen(stristr($value,'Message'))>0
&& !strlen(stristr($value,'Event'))>0
&& strlen(strpos($value,' '))>0) #remove blank lines
php_table($value);;
}
echo "</table>";
fclose($ami);
}
function php_table($value){
$row1 = true;
$value = explode(" ", $value);
foreach($value as $field){
if($row1){
echo "<tr><td>".$field."</td>";
$row1 = false;
}
else{
echo "<td>".$field."</td></tr>";
$row1 = true;
}
}
}
?>
答案 0 :(得分:4)
while (strlen($c = fread($fp, 1024)) > 0) {
$record .= $c;
}
编辑:您的应用程序挂起,因为它没有关闭连接以表示HTTP请求的结束。尝试
fwrite($ami, "Action: Status\r\n\r\n");
fwrite($ami, "Connection: Close\r\n\r\n");
答案 1 :(得分:4)
$data = '';
while (!feof($ami)) {
$data .= fread($ami, 1024);
}
或在php5中
$data = stream_get_contents($ami);
答案 2 :(得分:0)
只需使用循环并查找“文件结尾”
$record = '';
while( !feof( $ami ) ) {
$record .= fread($ami,9999);
}
您应该考虑使用较小的块。