fredcampbell fredcampbell - 1 month ago 8
PHP Question

Getting year attribute from JSON using PHP

I have successfully retrieved two attributes from this JSON page but i am having troubling with getting "years" attribute. I suppose problem is i am missing some parent element. I'd greatly appreciate if someone could point me in right direction, thanks. This is the link with JSON structure: http://api.edmunds.com/api/vehicle/v2/vins/WAUYP54B01N099265?fmt=json&api_key=XXX

You can see the result of the API in this eval.in

Here is the code:

<?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>

Answer

Years is an array. Try $mds = $jfo->years[0]->year;