【发布时间】:2019-02-12 09:19:27
【问题描述】:
当我想使用循环 foreach 将我的 json 数组解析为 php 对象时出现错误。
这是我的错误:
警告:为 foreach() 提供的参数无效 C:\xampp\htdocs\testJSON\crul_json.php 第 49 行
然后这是我的代码
<?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>
谁能帮我解决这个无效循环的错误? 谢谢:)
【问题讨论】:
-
var_dump($hasil)的输出是什么?以及为什么将其保存在变量$hdcode中? -
那是因为 $profile 是一个字符串,所以将其编码为字符串将解码为字符串,我还注意到您在解码中放入了
TRUE。这会将其解码为数组而不是对象
标签: php arrays json parsing object