Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch json fom url in php

Tags:

json

php

I am trying to make a php page tp print json data for this i m using one paraeter for which i needed to fetch json from another url.I used the code given in other stackoverflow ans but it always giving 0.I tried everything but it always giving 0.My php code is:

<?php
if(isset($_POST['add']))
{
require_once('loginConnect.php');



 $bookname=$_POST['bookname'];




$url = "http://example/star_avg.php?bookName=$bookname";
$json = file_get_contents($url);
$json_data = json_decode($json,TRUE);




 echo 'data' + $json_data->results[0]->{'num'};

?>

My json data from other url is: {"result":[{"avg":"3.9","num":"3"}]}

like image 516
Nicky Manali Avatar asked Mar 11 '23 07:03

Nicky Manali


1 Answers

You see 0 printed because you're performing an addition + between the string data and a non-existent property. In PHP, to concatenate strings, do not use +; instead, use the dot . operator

In addition, because you're using true as the 2nd parameter to json_decode, what you get back is an array of arrays. Use the array notation [] rather than the object notation -> to access members.

$json_data = json_decode($json,TRUE);
$num = $json_data['result'][0]['num']; //<- array notation
echo 'data: '.$num; //prints data: 3

Live demo

like image 148
BeetleJuice Avatar answered Mar 27 '23 07:03

BeetleJuice