[英]How to parse array JSON to PHP Object?
當我想使用循環foreach將json數組解析為php對象時出現錯誤。
這是我的錯誤:
警告:第49行的C:\\ xampp \\ htdocs \\ testJSON \\ crul_json.php中為foreach()提供了無效的參數
然后這是我的代碼
<?php
function http_request($url){
// persiapkan curl
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
// set user agent
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// tutup curl
curl_close($ch);
// mengembalikan hasil curl
return $output;
}
$profile = http_request("http://localhost/testWebService/");
//json_output(400, $profile);
$json_format = json_encode($profile);
//echo $json_format;
// ubah string JSON menjadi array
$hasil = json_decode($json_format, TRUE);
$hdcode = var_dump($hasil);
?>
<!DOCTYPE html>
<html>
<head>
<title>Curl Data JSON</title>
</head>
<body>
<br>
<p>
<?php
foreach ($hasil as $i):
?>
Nama: <?php echo $hasil->id_mhs; ?><br>
<?php endforeach;?>
</p>
</body>
</html>
誰能幫助我解決無效循環的此錯誤? 謝謝:)
是來自Web服務JSON的響應嗎? 如果是這樣,則不需要json_encode。
另外,由於將true作為第二個參數傳遞給json_decode,因此它將是數組而不是對象。 你可以打電話
$hasil = json_decode($json_format);
得到一個對象。
同樣在您的foreach中,您需要使用$i
而不是$hasil
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.