簡體   English   中英

從 json 中檢索特定值

[英]Retreive specific values from json

我正在嘗試從 json 數據中獲取特定值。我調用 web 服務並使用此代碼

<?php

//API Url
$url = 'http://myUrl/s1services';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
 'service' => 'login',    
 'username' => 'demo',
 'password' => 'demo',
 'appid' =>  '256'
);

//Encode the array into JSON.
$jsonData = json_encode($jsonData, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Set the compression type to gzip 
curl_setopt($ch,CURLOPT_ENCODING , "gzip");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch,CURLOPT_ENCODING , "utf-8");

//execute post
$result = curl_exec($ch);
curl_close($ch);

echo $result;



?>

我在下面的 json 中得到響應(我不知道為什么有些字段以二進制格式返回)

> {    "success":true,   
> "clientID":"9J8pJsP8KKnwH69V9JL4HNLKQrbpINb4SbDVOKPPG6X2JKbvLrLoM65ATqXLKYKrH2KtH5LLTaL5KdP0K4zPLNLOK2KrH5HGL6L4",
> "objs":[
>       {
>          "COMPANY":"1000",
>          "COMPANYNAME":"������� Demo ��",
>          "BRANCH":"1000",
>          "BRANCHNAME":"����� - ����",
>          "MODULE":"13",
>          "MODULENAME":"�������",
>          "REFID":"47",
>          "REFIDNAME":"����������� AE",
>          "USERID":"1",
>          "FINALDATE":"",
>          "ROLES":"",
>          "XSECURITY":"0",
>          "EXPTIME":""
>       }    ],    "ver":"5.00.520.11321",    "sn":"01100313514211",    "off":false,    "pin":false,    "appid":"256" }

我想獲取 clientID 和 COMPANYNAME 值。

我怎樣才能做到這一點?

謝謝你的幫助

通過使用json_decode()

$result_array = json_decode($result);

echo '<pre>';
print_r($result_array );
echo '</pre>';

echo "Client ID:".$result_array ->clientID;
echo "<br>";
echo "Client ID:".$result_array ->objs[0]->COMPANYNAME;

$result的格式為 json,因此您需要使用json_decode()將其轉換為數組。

因此您可以輕松導航和使用所有鍵和值。

我在本地 PC 上測試了您的 json 字符串, 在此處輸入圖像描述

這是我的 output,效果很好。 在此處輸入圖像描述

暫無
暫無

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

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