我正在使用以下代碼從我的 Web API 發送和檢索資料
//data
$data = array("Id_Empresa" => 1);
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
var_dump($data);
$json = json_decode($data);
foreach ($json->msg as $item) {
echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
}
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
這是我得到的回應
{"ok":true,"msg":[{"Nombre":"Carnicerias","Descripcion":"Comercio al por menor de carnes rojas","H_Open":"01:00:00","H_Close":"02:00:00"}]}bool(true)
我正在嘗試使用以下代碼訪問 JSON(因為它在類似的請求中對我有用):
$json = json_decode($data);
foreach ($json->msg as $item) {
echo "$item->Nombre, $item->Descripcion" . PHP_EOL;
}
但是正如您所看到的,變數 $data 不再是 JSON,而是變成了 bool(true)。
有誰知道我如何訪問 JSON msj 或為什么 $data 變數從 JSON 更改為 bool?
uj5u.com熱心網友回復:
PHP手冊的回傳值部分curl_exec說
成功時回傳真,失敗時回傳假。但是,如果設定了 CURLOPT_RETURNTRANSFER 選項,它將在成功時回傳結果,在失敗時回傳 false。
也許它可以更具體 - 該選項必須設定為true. 請參閱curl_setopt檔案中選項的定義:
true 將傳輸作為 curl_exec() 的回傳值的字串回傳,而不是直接輸出。
因此,您看到 JSON 回應是因為它直接由 輸出curl_exec,然后bool(true)因為curl_exec已回傳true到$data您要轉儲的變數。
改為設定CURLOPT_RETURNTRANSFER以true獲得您所期望的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321194.html
