4

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"}]}

3
  • try print_r() for $json_data, and display the result here Commented Aug 30, 2016 at 3:25
  • Since you have passed true while calling json_decode($json,true), you cannot access the data as object, try $json_data['results'][0]['num'] instead $json_data->results[0]->{'num'} Commented Aug 30, 2016 at 3:29
  • @ Rohit Khatri thank u it works Commented Aug 30, 2016 at 7:35

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

4 Comments

thank u very much it works perfectly.I need to ask one more ques that can i use more than pne url to fetch json differently
@NickyManali I don't understand the question
okk can i use more than one url to fetch json data.Like in above qus i have one url like that can i use two url in same php code to fetch json data.
@NickyManali sure. If you put the urls in to an array called $urls, you could then do foreach($urls as $url){...}. In each iteration of the loop, use $url to fetch and process the JSON from a new location

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.