2017-01-29 72 views
1

我試圖檢查twitch頻道是否存在。不知何故,如果一個頻道不存在,或者它被禁止了,那麼它會在$ result變量中顯示爲NULL。PHP twitch api檢查帳戶是否存在

但是,如果我直接檢查API,那麼響應將如下所示:

{"error":"Not Found","status":404,"message":"Channel 'd4newhatever2017' does not exist"} 

如何來到我的代碼返回NULL呢?有沒有人有想法?

代碼:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Twitch username checker</title> 
</head> 

<body> 
    <form method="post" enctype="multipart/form-data"> 
     <label for="file">Filename:</label> <input type="file" name="file" id="file"/> 
     <input type="submit" value="Check accounts"> 
    </form> 
    </br> 
</body> 

</html> 

<?php 
    if ($_FILES["file"]["error"] > 0) 
    { 
     echo "Error: " . $_FILES["file"]["error"] . "<br />"; 
    } 
    elseif ($_FILES["file"]["type"] !== "text/plain") 
    { 
     echo "File must be a .txt documet."; 
    } 
    else 
    { 
     $fp = fopen($_FILES['file']['tmp_name'], 'rb'); 

     while(($line = fgets($fp)) !== false) 
     { 
      getUserInformations($line); 
     } 
    } 

    function getUserInformations($account) 
    { 
     $client_id = 'xxx'; 
     $url = 'https://api.twitch.tv/kraken/channels/' . $account . '?client_id=' . $client_id; 

     $result = file_get_contents($url); 
     $result = json_decode($result, true); 

     if($result['error'] == 'Not Found') 
     { 
      echo 'Channel: ' . $account . 'does not exist. </br>'; 
     } 
     else 
     { 
      echo 'Channel: ' . $account . ' does exist and was created on the following date: ' . date('d-m-Y h:i:s ',strtotime($result["created_at"])) . '. </br>'; 
     } 
    } 
?> 

回答

0

這是絕對正常的。你必須定義ignore_errorsflagTrue如果你想獲取的不同狀態的結果比200

$result = file_get_contents(
    $url, 
    false, 
    stream_context_create(
     array(
      'http' => array(
       'ignore_errors' => true 
      ) 
     ) 
    ) 
); 
更換 $result = file_get_contents($url);