fredcampbell fredcampbell - 4 months ago 23
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:

You can see the result of the API in this

Here is the code:

// copy file content into a string var
if (isset($_POST['datvin'])){
$json_file = file_get_contents(''.$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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/style.css" />
<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">
<ul class="ul_json clearfix">

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

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


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