亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從測試站點返回的 JSON 字符串包含阻止 json_decode 工作的額外字符

從測試站點返回的 JSON 字符串包含阻止 json_decode 工作的額外字符

PHP
人到中年有點甜 2023-03-04 10:39:36
我正在嘗試了解如何在服務器之間傳輸數據。在線有一個包含 json 數據的測試 API。我嘗試了以下操作:-    <?php// Initiate curl session in a variable (resource) $curl_handle = curl_init();$url = "http://dummy.restapiexample.com/api/v1/employees"; // website sample API data// Set the curl URL option curl_setopt($curl_handle, CURLOPT_URL, $url);// This option will return data as a string instead of direct output curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);// Execute curl & store data in a variable $curl_data = curl_exec($curl_handle);curl_close($curl_handle);// Write the JSON string// echo $curl_data; // the above writes the JSON string ok// Now try decoding to PHP array$character = json_decode($curl_data); echo $character[1]->employee_name; // this throws an error 'Error: Cannot use object of type stdClass as array in C:\wamp64\www\curlex\curlget.php on line 24' ?>返回的字符串包含以下內容(為清楚起見,已刪除為 2 個條目):-    {"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""}]}我想 json_decode 由于{"status":"success","data":序言而失???請問如何解決?
查看完整描述

3 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

你的問題是,你已經從函數中省略了第二個參數json_decode(),如果沒有設置,它將把字符串解析為一個對象,而不是一個數組。


您可以在此處找到此功能的文檔,在您的情況下,您正在尋找的是參數assoc。


另一方面,您顯示的示例返回employee_name在另一個屬性內查找的內容,而不是在主要屬性(即data)中。


true嘗試作為函數的第二個參數提供:


$character = json_decode($curl_data, true);

echo $character[1]['employee_name'];

但這只有在數據示例不準確的情況下才有效。如果該示例準確無誤,要獲取employee_name第二個數據元素的 ,請使用:


$character = json_decode($curl_data, true);

echo $character['data'][1]['employee_name'];

注意,php 數組是從零開始的,所以如果你想從數組中取出第一個元素,你應該引用它的第 0 個屬性。


查看完整回答
反對 回復 2023-03-04
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

感謝所有提供幫助的人。我沒有意識到返回的字符串是一個二維數組。我被網站誤導了,它給了我免費提供的測試數據的鏈接。



查看完整回答
反對 回復 2023-03-04
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

您可以像這樣訪問它:


$character = json_decode($curl_data); 

echo $character->data[1]->employee_name; 


查看完整回答
反對 回復 2023-03-04
  • 3 回答
  • 0 關注
  • 120 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號