使用PHP从JSON获取year属性

时间:2016-10-31 12:25:57

标签: php json

我已成功从此JSON页面检索了两个属性,但我对获取“年”属性感到不安。我想问题是我错过了一些父元素。如果有人能指出我正确的方向,我将不胜感激,谢谢。这是与JSON结构的链接:http://api.edmunds.com/api/vehicle/v2/vins/WAUYP54B01N099265?fmt=json&api_key=XXX

您可以在this eval.in

中查看API的结果

以下是代码:

<?php
$datvin="";
$title="";
$posts="";
$mds="";
// copy file content into a string var
if (isset($_POST['datvin'])){
$datvin=trim($_POST['datvin']);
$json_file = file_get_contents('http://api.edmunds.com/api/vehicle/v2/vins/'.$datvin.'?fmt=json&api_key=XXX');
// convert the string to a json object
$jfo = json_decode($json_file);
// read the title value
$title = $jfo->make->name;
// copy the posts array to a php var
$posts = $jfo->make->id;
$mds= $jfo->years->year;

}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="header">

</div><!-- header -->
<h1 class="main_title"><?php echo $title; ?></h1>
<div class="content">
<form method="post">
<input type="text" name="datvin"><br>
<input type="submit">
</form>
<ul class="ul_json clearfix">
<?php

echo "$title<br>";
echo "$posts<br>";
echo "$mds";
?>
</ul>
</div><!-- content -->
<div class="footer">

</div><!-- footer -->
</div><!-- container -->
</body>
</html>

1 个答案:

答案 0 :(得分:2)

年是阵列。试试$mds = $jfo->years[0]->year;