我是php编程的新手.在我的项目中,我试图解析来自php web服务的JSON数据.这是Web服务中的代码.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
Run Code Online (Sandbox Code Playgroud)
这给了我这种JSON格式的数据.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Run Code Online (Sandbox Code Playgroud)
现在这是我的php页面代码.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
Run Code Online (Sandbox Code Playgroud)
我想在网页上显示内容.
我知道代码var_dump( $final_res );正在运行.但那段代码错了之后.我试图查看许多教程来找到解决方案,但没有找到任何人.我不知道我哪里错了.
第二个参数json_decode确定是否将结果作为数组而不是对象返回.由于您将其设置为true,因此结果是数组而不是对象.
$content = $final_res['articles'][0]['Content'];
Run Code Online (Sandbox Code Playgroud)