2017-03-18 94 views
0

我有简单的脚本从另一台服务器获取数据,每隔1分钟运行一次。fwrite之前检查数据

<?php 
$html = file_get_contents('http://google.com/data.php'); 


$myfile = fopen("data.html", "w") or die("Unable to open file!"); 

fwrite($myfile, $html); 
fclose($myfile); 

?> 

但有时,剧本写的空白数据data.html。我认为,因为我的服务器和远程服务器之间的连接问题,或目标文件只是有时空白。

我不知道如果我得到后检查数据,如果收到的数据不是空白然后写入,如果数据空白,然后退出。请帮我怎么做。谢谢!

+0

带有'empty'的'if'似乎可以工作,http://php.net/manual/en/control-structures.if.php http://php.net/manual/en/function.empty .PHP。 – chris85

+0

@ chris85不想成为迂腐,但“0”也算空 - 也许它可能是'data.php'脚本的有效输出... – ewcz

+0

@ewcz哦,好点,代码和描述不同。我认为这是HTML(data.html)。 – chris85

回答

0

file_get_contents回报false上的错误,所以你可以使用===!==作为

<?php 
$html = file_get_contents('http://google.com/data.php'); 

if($html !== false){ 
    $myfile = fopen("data.html", "w") or die("Unable to open file!"); 

    fwrite($myfile, $html); 
    fclose($myfile); 
} 

?> 

直接检查,如果你想仅仅测试输出是否为空,则可以使用例如比较$html !== false && $html !== ''