[英]API GET request values cannot set to variables and echo using curl json_decode in PHP
為什么我不能在這段代碼中回顯 $phone_number? 它說
未定義索引:phone_number。 但是當我回顯
$response
它返回值
<?php
$ch = curl_init( 'https://mighty-inlet-78383.herokuapp.com/api/hotels/imagedata');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
echo 'No responce';
}
// Decode the response
$responseData = json_decode($response);
// Print the date from the response
$phone_number = $responseData['phone_number'];
echo $phone_number;
?>
因為這些是 arrays 中的 arrays,所以您需要深入 go 以獲得所需的數據。 首先,確保使用“true”屬性將 JSON 作為數組返回:
$responseData = json_decode($response, true);
然后你可以得到第一個電話號碼(或通過改變數組索引的任何電話號碼):
echo $responseData[0]['phone_number'];
echo $responseData[1]['phone_number'];
您還可以遍歷響應:
foreach($responseData AS $response) {
echo $response['phone_number'];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.