2014-02-20 29 views
0

我需要處理空JSON請求,以防萬一用戶出錯。如何處理來自JSON的空數據

這裏是我的代碼:

$JSON = file_get_contents($url); 

//Puts the JSON var into a parameter that actually does the decoding into JSON 
$data = json_decode($JSON,true); 

echo $JSON; 
if ($JSON === ''){ 

header("Location: contact2.php"); 

}else{ 
//Execute the original plan 
} 

這裏是如果,不幸的是有沒有爲我工作報表的樂趣陣列:

if(is_array($data)) 

if($JSON === null) 

if($data === null) 

不勝感激任何幫助。

+2

解釋爲什麼它沒有工作。任何eny錯誤消息? –

+0

我對PHP相對來說比較新,如果我已經或者知道一個像樣的IDE和一個調試器,我總體上會更快樂一點,但問題會更少。從我的低估中,json_decode方法將其引入數組中。當我故意撞毀它時,我感到驚訝的是is_array方法對我不起作用。 – user3124081

回答

0

支票陣列的empty請參閱鏈路 http://in3.php.net/empty

+0

你會碰巧知道爲什麼當if語句爲真時,我的頭文件不會在本地重定向?我得到了if語句,它只是標題不會重定向到之前的論壇。感謝任何幫助。 – user3124081

+0

嘗試刪除此行echo $ JSON;並檢查 –

+0

或我需要檢查論壇上的JSON數據,才能進入下一頁? – user3124081

0

假設你使用PHP> = 5.3可以使用json_last_error以確定是否解碼成功:

if(json_last_error() === JSON_ERROR_NONE) { 
    // decoded fine 
} else { 
    // error decoding json 
} 
0

使用的GetType

if (gettype(json_decode($data))=='NULL'){ 
    //error handler here 
}