使用php读取Json数据响应


Read Json data response using php

如何使用php读取JSON数据响应?响应t是在第三方完成用户身份验证之后发出的。首先,我只想要displayNamepreferredUsername数据。

Json响应:

 {
      "stat": "ok",
      "profile": {
        "providerName": "testing",
        "identifier": "http://testing.com/58263223",
        "displayName": "testing",
        "preferredUsername": "testing",
        "name": {
          "formatted": "testing"
        },
        "url": "http://testing.com/testing/",
        "photo": "https://securecdn.testing.com/uploads/users/5826/3223/avatar32.jpg?1373393837",
        "providerSpecifier": "testing"
      }
    }

您可以使用json_decode(http://php.net/manual/en/function.json-decode.php)函数解码您的结果,然后检索值:

$json_data = '{
      "stat": "ok",
      "profile": {
        "providerName": "testing",
        "identifier": "http://testing.com/58263223",
        "displayName": "testing",
        "preferredUsername": "testing",
        "name": {
          "formatted": "testing"
        },
        "url": "http://testing.com/testing/",
        "photo": "https://securecdn.testing.com/uploads/users/5826/3223/avatar32.jpg?1373393837",
        "providerSpecifier": "testing"
      }
    }';
$json = json_decode($json_data);
echo $json->profile->displayName;
echo $json->profile->preferredUsername;
 <?php
$json='{
      "stat": "ok",
      "profile": {
        "providerName": "testing",
        "identifier": "http://testing.com/58263223",
        "displayName": "testing",
        "preferredUsername": "testing",
        "name": {
          "formatted": "testing"
        },
        "url": "http://testing.com/testing/",
        "photo": "https://securecdn.testing.com/uploads/users/5826/3223/avatar32.jpg?1373393837",
        "providerSpecifier": "testing"
      }
    }';

    $data=json_decode($json ,true);
     $preferredUsername=$data['profile']['preferredUsername'];
     $displayName=$data['profile']['displayName'];
    ?>

json_decode就是您想要的:

$json = '[
    {
        "displayName": "testing",
        "preferredUsername": "testing",
    }
]';
$jsonArray = json_decode($json);
foreach($jsonArray as $value){
    $displayName = $value->Display Name;
    $preferredUsername = $value->Preferred User;
}