2015-05-04 24 views
1

我有一個wordpress函數通過Zebra_cURL調用API,然後使用json_decode來適當地呈現數據。然而,有古怪行爲和下面的兩個錯誤發生:Trying to get property of non-object in [template file] on line 42,並通過線50爲對象提供的非對象&無效參數的JSON屬性

有問題的線都低於:

//Course display callback function 
function display_courses($result) { 
     $result->body = json_decode(html_entity_decode($result->body)); 
     $title = $result->body[0]->{'Title'}; 
     $term = $result->body[0]->{'Term'}; 
     $meetings = $result->body[0]->{'Meetings'}; 
     $status = $result->body[0]->{'Status'}; 
     $course_number = $result->body[0]->{'OfferingName'}; 
     $clean_course_number = preg_replace('/[^A-Za-z0-9\-]/', '', $course_number); 
     $credits = $result->body[0]->{'Credits'}; 
     $instructor = $result->body[0]->{'InstructorsFullName'}; 
     $description = $result->body[0]->{'SectionDetails'}[0]->{'Description'}; 
    } 

再後來我得到一個錯誤Invalid argument supplied for foreach() in [template file] on line 64是:

//Call callback function  
      function parse_courses($result) { 
       $result->body = json_decode(html_entity_decode($result->body)); 
       $course_data = array(); 
        foreach($result->body as $course) { 
        [code] 
      } 
        [more code] 
} 

我究竟做錯了什麼導致這些錯誤?

這是鏈接到the full template file。對於龐大的代碼轉儲道歉,但我有點在與我的頭。

回答

0

,必須始終驗證函數/方法輸出,如果結果,如果「預期
在你的情況,你沒有檢查什麼json_decode()返回

function parse_courses($result) { 
    $result = json_decode(html_entity_decode($result->body)); 
    if ((!is_array ($result) && !is_object($result)) || 
     (is_array($result) || count($result) == 0) || 
     (json_last_error() != JSON_ERROR_NONE)) { // only for PHP >= 5.3.0 

     // log the error or warning here ... 
     // $input = $result; 
     // $output = print_r ($result, TRUE); 

     // Only for PHP >= 5.3.0 
     // json_last_error(); 
     // json_last_error_msg(); 
     return -1; 
    } 
    $result->body = $result; 
    $course_data = array(); 
    foreach($result->body as $course) { 
     [code] 
    } 
    [more code] 
}