是否有办法从PHP中的URL获取json对象的值?



所以我试图从url获取json对象的值,当我在post man上点击那个url时,我得到了这样的东西

{
"error": "0",
"errorString": "",
"reply": {
"nonce": "5e415334832a8",
"realm": "VMS"
}
}

所以,我试图写一个php代码,显示nonce的值在浏览器中,但它不工作我有以下代码

$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect, true);
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;

我也做了这个

$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
echo $ch->reply[0]->nonce;

但它似乎仍然不起作用。

下面是您的2个代码示例和建议的更正。

使用file_get_contents:删除json_decode的第二个参数

$getNonceUrl = "https://example.com/api/getNonce";
$getContect = file_get_contents($getNonceUrl);
$jsonNoce = json_decode($getContect); // note removal of 2nd parameter
$dd = $jsonNoce->reply[0]->nonce;
echo $dd;

使用curl:您忘记使用json_decode解析curl输出

$ch = curl_init("https://example.com/api/getNonce");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data); // added this line, because curl doesn't decode json automatically
echo $ch->reply[0]->nonce;