如何解析json输出?

时间:2015-07-19 06:11:00

标签: php json parsing

我试图解析这个网址 https://esewa.com.np/epay/transdetails?pid=AddFund-C-11970239- 9625960&amt=100&scd=nprhosting&rid=00C3LF0

{
"code":"00",
"msg":"Success",
"txnDetail": {
                 "txnCode":"00C3LF0",
                 "amt":"100.0",
                 "date":"2015-07-16 23:44:18.0",
                 "payerId":"dipsnwc@gmail.com",
                 "status":"COMPLETE",
                 "pid":"AddFund-C-11970239-9625960",
                 "txAmt":"0",
                 "psc":"0",
                 "pdc":"0"
             }
  }

喜欢这个

$fields = array(
'pid' => "AddFund-C-11970239-9625960";
'amt' => "100.0";
'scd' => "nprhosting";
'rid' => "00C3LF0"; 
);


$field2 = json_encode($fields);

$url = "https://esewa.com.np/epay/transdetails";

 // Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data 
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $field2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($field2))
);
// Execute post
$result = curl_exec($ch);

// Close connection
curl_close($ch);
//

///Deocde Json
$data = (json_decode($result, true));
var_dump($data);
$message =$data['msg']; 
$status =$data['txnDetail']['status'];
echo $message;
echo $status;

仍然没有输出??

2 个答案:

答案 0 :(得分:0)

数组不正确,请删除:

$fields = array(
'pid' => "AddFund-C-11970239-9625960",
'amt' => "100.0",
'scd' => "nprhosting",
'rid' => "00C3LF0"
);

并尝试

$url = "http://examplesite.com/epay/transdetails?" . http_build_query($fields);

查看POSTFIELDSHTTPHEADER

curl_setopt($ch, CURLOPT_POST, false);

参数应该是GET(根据你提供的链接),保持简单。

同时检查this答案,以便更好地了解如何使用PHP CURL发送HTTP GET请求。

答案 1 :(得分:0)

我尝试了并且工作了..

$url = 'https://example.com/epay/transdetails?pid=AddFund-C-11970239-9625960&amt=100&scd=nprsite&rid=00C3LF0';
$data  = file_get_contents($url);
$arr =  json_decode($data,true);
echo $arr['txnDetail']['status'];
print_r($arr);