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"}]}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With