簡體   English   中英

有沒有辦法從 PHP 中的 URL 獲取 json 對象的值?

[英]Is there a way to get value of json object from a URL in PHP?

所以我試圖從一個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;

暫無
暫無

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

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