我刚开始使用json进行实际工作,并试图尽可能地学习!我想分享我所做的这项工作,我觉得这可能需要一些改进,如果不是很多。json_decode响应是否为空
那么好吧,我用twitch.tv REST_API。这是我的代码。基本上我想通过我的网络托管公司运行这个每分钟作为一个crontab。我知道你可以通过这种方式获得(编码)JSON数据:“http://api.justin.tv/api/stream/list.json?channel=example,example2,example3”;以及。它可能更快?但后来我不知道如何在数据库中设置我的流离线。
所以我想我是问我如何能改善这一点。
$result = mysql_query("SELECT streamname FROM streams") or die(mysql_error());
$ids=array();
while($row = mysql_fetch_assoc($result))
{
$ids[]=$row["streamname"];
}
$mycurl = curl_init();
for($i=0;$i<count($ids);$i++)
{
curl_setopt ($mycurl, CURLOPT_HEADER, 0);
curl_setopt ($mycurl, CURLOPT_RETURNTRANSFER, 1);
$url = "http://api.justin.tv/api/stream/list.json?channel=$ids[$i]";
curl_setopt ($mycurl, CURLOPT_URL, $url);
$web_response = curl_exec($mycurl);
$result = json_decode($web_response);
if(empty($result))
{
$sql = "UPDATE streams SET online = '0' WHERE streamname = '" . $ids[$i] . "'";
}
else
{
$sql = "UPDATE streams SET online = '1' WHERE streamname = '" . $ids[$i] . "'";
}
mysql_query($sql) or die(mysql_error());
}
您正在使用[an **过时的**数据库API](http://stackoverflow.com/q/12859942/19068)并应使用[现代替换](http://php.net/manual/) EN/mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com/)**,现代的API会使[防御]更容易(http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php)自己从。 – Quentin