簡體   English   中英

JSON元素返回NULL

[英]JSON element returning NULL

我是JSON新手,遇到錯誤時檢查獲取錯誤消息時遇到問題。 當結果不是錯誤時,我的代碼可以正常工作,因此我在某種程度上了解我在做什么。
這是我嘗試解析的錯誤JSON:

{
   "error": {
      "message": "Unsupported get request.",
      "type": "GraphMethodException",
      "code": 100
   }
}

這是我失敗的代碼:

$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
//valid $jsonurl = "http://graph.facebook.com/WhitworthACM";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

var_dump($json_output);
// This returns NULL


if (property_exists($json_output->error)) {
        echo "<p>error: $json_output->error->{'message'} </p>";
    } else {
        echo "<p>no error :(</p>";
}

$facebook_id = $json_output->{'id'};
$facebook_name = $json_output->{'name'};
$facebook_link = $json_output->{'link'};

因為url返回400 Bad Request

默認情況下,當http狀態代碼為400時,不能使用file_get_contents函數獲取響應內容。

您需要將ignore_errors選項設置為true

$opts = array(
  'http'=>array(
    'ignore_errors' => true
  )
);
$context = stream_context_create($opts);
$jsonurl = "http://graph.facebook.com/JubilationDanceMinistry";
$json = file_get_contents($jsonurl, false, $context);
var_dump($json);

您不能使用字符串插值將多個->在一起。

您將不得不傳遞多個參數以進行echo或字符串連接:

    echo "<p>error: ", $json_output->error->{'message'}, " </p>";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM