繁体   English   中英

如何将数组JSON解析为PHP对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM