我有這樣的迴應:如何獲得API響應
{
"Contratos": [
{
"IdCUPS": 0,
"CodigoCUPS": "",
"IdContrato": 0,
"CodigoContrato": null,
"IdCliente": 0,
"IdDocumento": null,
"IdEmpresa": null,
"Incidencias": [
{
"Propiedad": "CodigoCUPS",
"Code": 0,
"CodeAlfa": "",
"Mensaje": "El cups ya esta asignado a contratos activos",
"IsAdvertencia": false,
"IsError": true,
"IsExcepcion": false,
"ExceptionTimestamp": "0001-01-01T00:00:00",
"ExceptionMessage": "",
"ExceptionStackTrace": "",
"InnerException": "",
"ImageSource": ""
}
]
}
]
}
如何訪問到「Mensaje」選項? 我有這樣的代碼,我做curl_init及其選項:
$ch = curl_init($url.$contratoPotencial);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
我這個代碼的嘗試:
echo "<br><br> Mensaje: ";
echo "<br>".$response->Contratos->Incidencias->Mensaje;
但它不工作!
爲什麼該代碼有工作的希望嗎?閱讀[關於數組如何工作的手冊](http://php.net/manual/en/language.types.array.php)。還要注意'Incidencias'是一個常規數組,因此您需要引用元素0,而不僅僅是跳過它,就好像它不在那裏一樣。 – tadman
嘗試通過它,看看你實際上在做什麼,'var_dump($ response)'等等。你有對象和數組的混合,並且使用這些的語法各不相同(你試圖使用每個子項作爲一個對象) – JimL
試試'$ data = json_decode($ response);' – manian